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?
Asked
Active
Viewed 1.5e+01k times
95
-
1how do you save your application data? – kumar_android Mar 22 '13 at 07:06
-
In a local DB, as well as JSON files. I have managed to clear the data successfully so far – Ryan Mar 22 '13 at 07:11
-
Check these question/answer http://stackoverflow.com/questions/2470870/force-application-to-restart-on-first-activity-android – Zelldon Mar 22 '13 at 07:15
-
1I 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. – Ishwor Khanal Aug 12 '17 at 08:29
-
You can use 'restart_app' plugin which uses native APIs to restart the app in OS level. – Hossein Yousefpour May 31 '23 at 05:11
1 Answers
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);

Balthazar Rouberol
- 6,822
- 2
- 35
- 41

Code_Life
- 5,742
- 4
- 29
- 49
-
1
-
2
-
it works perfectly, except that is takes time, like 2-3 seconds, any solution to reduce that restart time ? – Kishita Variya Dec 20 '18 at 06:19
-
4@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 Jan 27 '19 at 09:40
-
-
@Kishita I came across [this article](https://medium.com/mindorks/enable-background-services-in-chinese-roms-32e73dfba1a6) which might be helpful. I haven't tried that yet though – Kathir Feb 08 '19 at 11:08
-
-
Bit off topic, but it maybe helps someone. Running this with a 500-1000ms delayed Handler is a good idea if you have issues with loading sharedpreferences on startup. I used this restart during theme change. User picks the new theme, if it's different then the old one, restart the app. But without the delay the new theme setting wasn't saved into the DefaultSharedPreferences. So even the user changed the theme, the change wasn't saved in time. – S0und Nov 28 '19 at 16:52
-