I am using the following code to minimize my app
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
but now I want to minimize my app after some specific time. I mean my app should minimize automatically after 40 - 60 secs etc. I am trying to achieve this through AlarmManager but it is not working.
How I can send my activity to background?
Put the following code in MainActivity.java
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
test();
}
});
}
}, 0, 20000);
The above code will call test() function after 20 second.. Now write the following function...
public void test()
{
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Hope this will help.
Related
I'm developing a countdown app, and currently trying to show a notification when you exit the app while the countdown is running. Correspondingly, I want the notification to disappear when the user returns to the app.
So far I've managed to make it work for a simple notification with static text, do the following: in MainActivity.java, in onStop(), I create an intent and initiate the service with startService(intent). Symmetrically, in onStart() I run stopService(intent) so that when you return to the app the service gets canceled. This works like a charm, the notification appears and disappears when it must.
The next step has been trying to make the notification show a text that varies (it will say "X minutes remaining"). According to the info out there, to update an existing notification you have to create a new one, give it the same ID as the existing one, and call .notify of a NotificationManager. When I do this the notification indeed gets updated correctly (the text changes as expected), BUT: now, returning to the main activity does not cancel the notification. The icon stays up there and doesn't get interrupted.
I've been trying to solve this for hours and hours. I've also tried hacks like sending signals via shared preferences to tell the service to stop, but for some reason, it seems to completely ignore the command stopself() too.
Does anybody have a suggestion of what could be the cause? Any help would be greatly appreciated. Here is the relevant code:
MainActivity.java:
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(getBaseContext(), CounterService.class);
stopService(serviceIntent);
}
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(getBaseContext(), CounterService.class);
startService(serviceIntent);
}
CounterService.java:
public class CounterService extends Service {
Notification notification;
NotificationManager notificator;
Intent intentNoti;
CountDownTimer counter;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
intentNoti = new Intent(this, MainActivity.class);
final PendingIntent pending = PendingIntent.getActivity(this, 0, intentNoti, 0);
final Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.common_full_open_on_phone);
//Countdown
counter = new CountDownTimer (30000, 1000) {
public void onTick(long millisUntilFinished) {
String time = String.valueOf(System.currentTimeMillis());
notification = new Notification.Builder(CounterService.this)
.setContentTitle("Name")
.setContentText(time)
.setSmallIcon(R.drawable.icon_start)
.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pending)
.setOngoing(true).build();
notificator = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificator.notify(1001, notification);
}
public void onFinish() {
}
}.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
counter.cancel();
}
}
First create a Timer like this
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
timerTask = new TimerTask() {
public void run() {
// Add your code
}
};
timer.schedule(timerTask, 1000, 1000); //
}
Also you need to stop your timer.
So
public void stoptimertask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
Call StartTimer and StopTimer in OnStartCommand() and onDestroy() respectively. Add these lines in onDestroy()
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
it can be handled in multiple ways, you have not stopped your timer
Note:- posting code in Kotlin
1)
override fun onDestroy() {
counter.cancel()
}
in your activity
override fun onResume() {
super.onResume()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancelAll()
}
I have an application in which I'm receiving a sms containing his location.On receiving sms it calls another activity to start and passes that location to that activity to plot it on the map.Before calling the second activity it shows a toast like notification on the screen but somehoe due to calling second activity that toast doesn't come up.My question is how can we delay the calling of second activity from this activity ?
You can use something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(SearxhJobs.this,JobsTypes.class);
startActivity(i);
}
}, 5000);
Here it waits upto 5 seconds to launch activity.
Hope it helps
You can do it with a Handler like this
Handler h = new Handler(){
#Override
public void handleMessage(Message msg) {
Intent i = new Intent().setClass(ctx, MainActivity.class);
startActivity(i);
}
};
h.sendEmptyMessageDelayed(0, 1500); // 1500 is time in miliseconds
Make an AsyncClass that does Thread.sleep() in the doInBackground() method, then navigate to your new activity in the your onPostExecute() method.
Call your toast message and then execute the AsyncClass.
For Kotlin
Handler().postDelayed({
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}, 5000)
Try:
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment then use getActivity() as the context.
startActivity(new Intent(SplashActivity.this, MainActivity.class));
// To close the CurrentActitity, r.g. SpalshActivity
finish();
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Simply set the layout!
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.next); //where <next> is you target activity :)
}
}, 5000);
An example would be the following:
Handler TimeDelay=new Handler();
if(previous=="geofence"){
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
Runnable r = new Runnable() {
#Override
public void run() {
/*
Intent intent = new Intent(
MyBroadcastMessageReceiver.class.getName());
intent.putExtra("some additional data", choice);
someActivity.sendBroadcast(intent);*/
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
}
};
TimeDelay.postDelayed(r, 150000);
I want to recall an activity after 12 minutes whole the times who get my JSON but i don't know how use timertask and timershedule can you help me please?
I try this but isn't work
my program:
public class recuperationJson extends AppCompatActivity implements getData.ReturnValue {
private getData data;
private TextView t;
private String json_string;
private String json_url = "http://192.168.0.14/projet/php/fichier.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
data = new getData(json_url);
data.setReturnListener(this);
data.execute((Void) null);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new Testing(), 0,5000);
}
#Override
public String renvoyerValeurString(String valeurARenvoyer) {
data = null;
//Ici je récupère directement mon json contenu dans la variable valeurARenvoyer
json_string = valeurARenvoyer;
Intent intent = new Intent(this,Accueil.class);
intent.putExtra("json_data", json_string);
startActivity(intent);
// Toast.makeText(this, json_string, Toast.LENGTH_SHORT).show();
return json_string;
}
public class Testing extends TimerTask {
public void run() {
Toast.makeText(recuperationJson.this, "test", Toast.LENGTH_SHORT).show();
}
}
My log
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.suprem.projetfinal, PID: 3196
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.suprem.projetfinal.recuperationJson$Testing$override.run(recuperationJson.java:48)
at com.suprem.projetfinal.recuperationJson$Testing$override.access$dispatch(recuperationJson.java)
at com.suprem.projetfinal.recuperationJson$Testing.run(recuperationJson.java:0)
at java.util.Timer$TimerImpl.run(Timer.java:284)
This works for me. In calling class schedule your timer.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new Testing(), 0,5000);
in the testing class perform your activity
import java.util.TimerTask;
public class Testing extends TimerTask
{
public void run()
{
//your task here
}
}
Timer doesn't work once server get shutdown or restart. Better to use quartz.
There are 2 methods come up with my mind.
1 - Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
System.out.println("RUN AFTER 12 minutes");
}
}, 12*60*1000);
2 - AlarmManager
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive( Context context, Intent _ )
{
System.out.println("RUN AFTER 12 minutes");
context.unregisterReceiver( this );
}
};
registerReceiver( receiver, new IntentFilter("message") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("message"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60*1000*12, pintent );
So I am developing a simple app for a college project, And I have been able to integrate a Facebook login using fragments.
But I now am stuck trying to redirect the user after they login. I simply want to redirect them to the second activity page
Here is my code for the Facebook login success
private FacebookCallback<LoginResult> mCallback=new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
display.setText("Welcome: " + profile.getFirstName());
//Redirect to Second Activity
}
}
To make a delayed transition use Handler class's postDelayed(Runnable r, long delayMillis) method, for example:
Java
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment
// then use getActivity() as the context.
startActivity(new Intent(CurrentActivity.this, TargetActivity.class));
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Kotlin with Anko
val someThread = Runnable {
startActivity(intentFor<TargetActivity>())
}
Handler().postDelayed(someThread, 1500)
Simply call a new activity through intent:
Intent i = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(i);
finish();
Check this:-
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(CurrentActivity.this,Next.class);
startActivity(i);
}
}, 3000);
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each Handler instance is
associated with a single thread and that thread's message queue. When
you create a new Handler, it is bound to the thread / message queue of
the thread that is creating it -- from that point on, it will deliver
messages and runnables to that message queue and execute them as they
come out of the message queue.
You can use Handler postDelayed Method easily .
Handler hd = new Handler();
hd.postDelayed(new Runnable() {
#Override
public void run() {
// Add Your Intent
}
}, 2000); // Time Delay ,2 Seconds
}
In Kotlin;
val r = Runnable {
startActivity(Intent(this, AuthorActivity::class.java))
}
val h = Handler()
h.postDelayed(r, 10)
Hey I am doing a simple Android app and I am trying to a start new activity from a thread like this:
public void startUI (){
Thread t = new Thread(){
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
startActivity(goToMenu);
}
});
;}
};
t.start;
}
But when my code comes to this line
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
It crashes and writes: "application stopped working".
If you want to start an activity you need to use Activity context as a first parameter. If you use Application context then your MainMenu activity must have a FLAG_ACTIVITY_NEW_TASK flag set. You cannot start new activity in the same task from application context.
Refer: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NEW_TASK
As #Raghunandan mentioned, if you want a delay, you should use a Handler like this:
uiHandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent goToMenu = new Intent(getApplicationContext(), MainMenu.class);
goToMenu.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(goToMenu);
}
}, 500);