Reputation: 3154
This is pretty start forward. I have a situation where I need to restart the app after clearing the shared preferences so this is what I do
sp.edit().clear().apply();
Intent mStartActivity = new Intent(context, IntroActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
but it clears the sp when I just use
sp.edit().clear().apply();
and then go ahead and restart the application manually, can someone explain me how I can fix this so I can automatically restart the application without the user needing to do it manually?
Upvotes: 1
Views: 39
Reputation: 17834
Use commit()
instead of apply()
.
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
Like the documentation states, apply()
is asynchronous, and might not start immediately. If you call it and then immediately kill your process, it has no time to actually save the changes you made to disk.
commit()
, on the other hand, will block the current Thread until the operation is complete, making sure System.exit(0)
doesn't interrupt it.
Upvotes: 2