Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to commit application settings to SharedPreferences (onStop or onDestroy)

Tags:

android

I was wondering, when is the suitable time to save our application settings to SharedPreferences. Should we do it during onStop, or onDestroy? I realize both methods have their pros and cons.

onStop

If user intention is not quitting the application, save application settings to SharedPreferences just seem to be redundant. He merely press home (onStop called) -> long press home -> relaunch application by select the application again

onDestroy

User can kill the application by press home (onStop called) -> long press home -> swipe left on the application to kill it. If user quit the application by that way, I realize onDestroy is not being called although the app is killed. Hence, application settings is not being saved.

So, is it better to save the application settings, during onStop or onDestroy?

like image 622
Cheok Yan Cheng Avatar asked Feb 07 '13 17:02

Cheok Yan Cheng


1 Answers

It is best to call commit() either right after you've made the changes, or in the onPause() method. This ensures that your changes are saved in pretty much every scenario, except uncaught exceptions that crash your app.

Also, you should note that neither onStop() or onDestroy() are guaranteed to be called at all, particularly in situations when Android is low on memory. However, onPause() is almost always called.

like image 161
Raghav Sood Avatar answered Sep 18 '22 20:09

Raghav Sood