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

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 ?


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.


I Think Android documentation explains pretty much when you should be comiting or persisting any data from user:

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

http://developer.android.com/reference/android/app/Activity.html

链接地址: http://www.djcxy.com/p/90802.html

上一篇: 对Android活动生命周期的困惑

下一篇: 何时将应用程序设置提交给SharedPreferences(onStop或onDestroy)