Android: Saving a state during Android lifecycle

后端 未结 3 1295
隐瞒了意图╮
隐瞒了意图╮ 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.

    0 讨论(0)
  • 2020-12-19 20:35

    Your ListView should not be cleared after returning from the Pref screen unless the Activity has been destroyed while the Pref screen was showing (in which case onCreate should have been called with the saved bundle).

    The savedInstanceState is only used when the Activity has been destroyed and needs to be recreated. In this case, it looks like your ListActivity has not been destroyed.

    Are you clearing your ListView manually somewhere?

    0 讨论(0)
  • Probably a bad answer, but are you sure onRestoreInstanceState needs to be called?

    The point of the bundle and onSaveInstanceState / onCreate with bundle / onRestoreInstanceState is to save transient data for an activity that is in the history stack, in case the activity must be killed to reclaim some memory. If it is killed, the activity can be restored, as if it were never killed, via onCreate / onRestonreInstanceState. However, if the activity was not killed, there may be no need to restore its transient data - presumably it is just as it was.

    The Android documentation is careful to point out that onSaveInstanceStae / onRestoreInstanceState are not lifecycle methods, so aren't guaranteed to be called during lifecycle state transitions. If you need to hook into certain lifecycle transitions, take a look at the lifecycle hook methods. For example, onResume is called when the activity becomes the foreground activity and onPause is called when it is no longer the foreground activity.

    Android Lifecycle Picture

    0 讨论(0)
提交回复
热议问题