For an unknown reason, I can't get my application leaving properly so that when I push the home button and the app icon again, I resume where I was in the app. I would like to force the application to restart on the first Activity.
I suppose this has something to do with onDestroy() or maybe onPause() but I don't know what to do.
It is important to check that the first activity which opens when the app is launched is MainActivity. java (The activity which we want to appear only once). For this, open the AndroidManifest. xml file and ensure that we have the intent-filter tag inside the activity tag that should appear just once.
In order to restart your application when it crashed you should do the following : In the onCreate method, in your main activity initialize a PendingIntent member: Intent intent = PendingIntent. getActivity( YourApplication.
Here is an example to restart your app in a generic way by using the PackageManager:
Intent i = getBaseContext().getPackageManager() .getLaunchIntentForPackage( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i);
The solution marked as 'answer' works but has one disadvantage that was critical for me. With FLAG_ACTIVITY_CLEAR_TOP your target activity will get onCreate called before your old activity stack receives onDestroy. While I have been clearing some necessary stuff in onDestroy I had to workaroud.
This is the solution that worked for me:
public static void restart(Context context, int delay) { if (delay == 0) { delay = 1; } Log.e("", "restarting app"); Intent restartIntent = context.getPackageManager() .getLaunchIntentForPackage(context.getPackageName() ); PendingIntent intent = PendingIntent.getActivity( context, 0, restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP); AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent); System.exit(2); }
The idea is to fire a PendingIntent via AlarmManager that will be invoked a bit later, giving old activity stack some time to clear up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With