95

I'm trying to create a 'log out' function within my application. Basically, by logging out, the application data should be cleared. What I would like to do is after logging out, the application should restart so that credentials etc. can be entered again. The problem I'm having is that at the point of the user clicking 'log-out', the application already has 3-4 activities running, and I'm not sure how to step back through them. How do I (simulate?) a restart of the app?

5
  • 1
    how do you save your application data? Commented Mar 22, 2013 at 7:06
  • In a local DB, as well as JSON files. I have managed to clear the data successfully so far Commented Mar 22, 2013 at 7:11
  • Check these question/answer stackoverflow.com/questions/2470870/… Commented Mar 22, 2013 at 7:15
  • 1
    I wonder is it good practice to use System.exit(0) to restart the application and release all static variables and destroy fragment view? If not can you please suggest me the right way to do this. I got the same problem as you had. Thank you. Commented Aug 12, 2017 at 8:29
  • You can use 'restart_app' plugin which uses native APIs to restart the app in OS level. Commented May 31, 2023 at 5:11

1 Answer 1

70

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Sign up to request clarification or add additional context in comments.

9 Comments

Working solution
Will the same code work for Nougat as well??
it works perfectly, except that is takes time, like 2-3 seconds, any solution to reduce that restart time ?
@Kishita. I don't think so. I'm quite surprised that it actually works now in 2019 considering the difficulties one has to face to set an exact Alarm. Some Chinese ROMs (ex. OnePlus) block such Alarms.
@Kathir then what shall I use ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.