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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With