Force application to restart on first activity
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.
Solution 1:
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);
Solution 2:
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.
Solution 3:
if you want to always start at the root you want to set android:clearTaskOnLaunch to true on your root activity
Solution 4:
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
Use this property in manifest file in starting class (first activity).
Solution 5:
Does FLAG_ACTIVITY_CLEAR_TOP do what you need to do?
Intent i = new Intent(getBaseContext(), YourActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);