When exactly are onSaveInstanceState() and onRestoreInstanceState() called?

前端 未结 5 1377
梦如初夏
梦如初夏 2020-11-28 20:14

The following figure (from the official doc) describes the well-known lifecycle of an Android activity:

5条回答
  •  独厮守ぢ
    2020-11-28 20:24

    This is an extra information for onSaveInstanceState(Bundle)

    from docs

    Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

    So it's default implementation for..

    The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.

提交回复
热议问题