11

I need to restart the app programmatically. My launcher activity is called 'Login' and after login, the main activity is called 'Main'. From within the main activity I want to restart the app. So I have the following:

Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

This will show the 'Login' activity, however when I press back I'm returned back to the previous activity.

Is there a better way to really restart the app?

N J
  • 27,217
  • 13
  • 76
  • 96
Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

2 Answers2

25

Try below code

Intent i = getBaseContext().getPackageManager().
           getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

And another thing before calling your second Activity call

finish();
johnrao07
  • 6,690
  • 4
  • 32
  • 55
2

Try this

call finish()

Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
N J
  • 27,217
  • 13
  • 76
  • 96