If I, for example, need to keep some very important data which the user can edit within my app, should I need to save them every time user changes such data or is it ok if I would save it within onPause(), onStop() or onDestroy() methods?
Can somehow application end without any of those methods calling? (For instance when battery runs out)

- 1,125
- 8
- 23

- 83
- 3
-
Your application may crash and the user may drop the phone resulting in the back cover and battery flying away. In both cases the `Activity` life cycle methods are skipped and unsaved very important data in the phone's RAM is lost. I don't know what happens when the device runs out of battery but [this older answer](https://stackoverflow.com/questions/27845728/what-android-methods-are-called-when-battery-dies) suggests that `onDestroy()` is called. – Markus Kauppinen Oct 28 '16 at 11:17
4 Answers
This certainly can't be done in onDestroy(). According to the documentation:
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
So yes, the application can end without calling any of the lifecycle methods.

- 2,249
- 3
- 21
- 31
In that scenario when the phone is shutting down, you can use the ACTION_SHUTDOWN Intent. More info here. For all other cases onPause should do the work. Even in the link provided, there is a statement that onPause will be called if the app is in FG.
Apps will not normally need to handle this, since the foreground activity will be paused as well.
However, if it is not so expensive operation, I would go with saving data after edit.

- 488
- 3
- 10
As per the documentation of Android activity life cycle, onPause
is called when an activity is going into the background, but has not (yet) been killed.
Hence, in most Android documentation, and sample codes you will find onPause
is used for saving any persistent state the activity is editing, to present a "edit in place" model to the user and making sure nothing is lost if there are not enough resources.
So in your use case, all you need to do is implement onPause
for your Activity
and write a code to Save the activity state (EditText
content or any other ongoing user interactions). Android system will save the activity state which you can always get back in onCreate
of your Activity when android launch your activity next time.

- 6,077
- 11
- 38
- 58
in this case please verify your phone activity via debug interface , some of phones are terminate your application this is force quit.

- 36
- 1