深入理解onSaveInstanceState和onRestoreInstanceState

来源:互联网 发布:爱普生mp288清零软件 编辑:程序博客网 时间:2024/06/06 07:19

作用

onSaveInstanceState用于保存Activity中每个实例的状态;onRestoreInstanceState用于恢复Activity异常销毁之前的状态,也就是onSaveInstanceState保存的状态。

使用时机

一般只有当Activity非自然退出时,才会调用onSaveInstanceState。如:
1. 点击Home键,退出应用
2. 横竖屏切换
3. 点击电源按钮,进入锁屏状态
4. 跳转到其他Activity时

代码如下:

protected void onSaveInstanceState(Bundle outState) {        outState.putBundle(WINDOW_HIERARCHY_TAG, mWindow.saveHierarchyState());        Parcelable p = mFragments.saveAllState();        if (p != null) {            outState.putParcelable(FRAGMENTS_TAG, p);        }        getApplication().dispatchActivitySaveInstanceState(this, outState); }

可以看到,一共保存了两种数据:
1. mWindow.saveHierarchyState:主要是一些获取了焦点的UI组件(有的博客说组件必须具有ID,但我实际测试发现并非如此)
2. mFragments.saveAllState:组件状态,如EditText输入的内容等

当Activity从之前的状态重新初始化时,会调用onRestoreInstanceState,不过大部分的数据恢复操作是在onCreate(Bundle saveInstanceBundle)中实现的。代码如下:

protected void onRestoreInstanceState(Bundle savedInstanceState) {        if (mWindow != null) {            Bundle windowState = savedInstanceState.getBundle(WINDOW_HIERARCHY_TAG);            if (windowState != null) {                mWindow.restoreHierarchyState(windowState);            }        } }
 protected void onCreate(@Nullable Bundle savedInstanceState) {        ...        if (savedInstanceState != null) {            Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);            mFragments.restoreAllState(p, mLastNonConfigurationInstances != null                    ? mLastNonConfigurationInstances.fragments : null);        }        mFragments.dispatchCreate();        getApplication().dispatchActivityCreated(this, savedInstanceState);       ...    }

为什么要放到onCreate和onRestoreInstanceState两个方法里恢复数据呢?官方解释如下:

Most implementations will simply use {@link #onCreate} to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation.

也就是说,onRestoreInstanceState主要是用于子类继承的。

生命周期中的顺序

onSaveInstanceState运行于onStop之前,至于和onPause的前后关系则不一定,一般来说位于onPause之后,onStop之前。
onRestoreInstanceState运行于onStart和onPostCreate(Activity启动完成时调用,位于onStart之后)之间。

阅读全文
1 0
原创粉丝点击