Android: Saving a state during Android lifecycle

后端 未结 3 1308
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 20:14

I am refering to http://developer.android.com/reference/android/app/Activity.html.

I have an activity which can be \"interrupted\" by the user, e.g. the user opens

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 20:23

    Have a look at the Application Fundamentals, specifically this part:

    Unlike onPause() and the other methods discussed earlier, onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state.

    Because onSaveInstanceState() is not always called, you should use it only to record the transient state of the activity, not to store persistent data. Use onPause() for that purpose instead.

    Basically, any persistant data should be written out in your onPause() method and read back in onResume(). Check out the Data Storage article for ways of saving data.

提交回复
热议问题