Force application to restart on first activity
if you want to always start at the root you want to set android:clearTaskOnLaunch to true on your root activity
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
Use this property in manifest file in starting class (first activity).
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.