onSaveInstanceState

作用

onSaveInstanceState的作用是用来保存Activity的状态,避免再次回到Actviity时数据丢失,比较常见的是表单输入页面。

调用时机

假设用户当前的页面是ActivityA,经过测试在以下几种情况下系统会调用onSaveInstanceState

1,用户按下home键

2,用户唤起历史任务,并选择某个任务(其他app)

3,用户按下电源键

4,屏幕方向切换

5, 在不finish的前提下,ActivityA启动ActivityB

生命周期

假设当前的页面是ActivityA,按下home键后生命周期执行情况如下

onCreate->onStart->onResume
onPause->onSaveInstance->onStop

这时ActivityA处于后台,根据系统的内存状态决定了ActivityA是否会被强制销毁。
如果系统内存不足,强制ActivityA销毁,当用户回到ActivityA时,生命周期如下:

onCreate->onStart-> onRestoreInstanceState->onResume

NOTE:onCreate中的bundle不为null,可以从bundle中恢复数据,也可以从onRestoreInstanceState中恢复数据
模拟Activity销毁的方法:
1,开发者选项不保留活动
2,第三方工具的一键清理

如果系统内存充足,ActivityA未被销毁,当用户回到ActivityA时,生命周期如下:

onRestart->onStart->onResume

Activity的代码执行情况如下:
1,performResume

final void performResume() {
        performRestart();//----------------注意

        mFragments.execPendingActions();

        mLastNonConfigurationInstances = null;

        mCalled = false;
        // mResumed is set by the instrumentation
        mInstrumentation.callActivityOnResume(this);//对应Activity的onResume
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onResume()");
        }
        ......

        // Now really resume, and install the current status bar and menu.
        mCalled = false;

        mFragments.dispatchResume();
        mFragments.execPendingActions();
        ......
    }

2,performRestart

final void performRestart() {
        mFragments.noteStateNotSaved();

        if (mStopped) {
            mStopped = false;
            if (mToken != null && mParent == null) {
                WindowManagerGlobal.getInstance().setStoppedState(mToken, false);
            }
            ......
            mCalled = false;
            mInstrumentation.callActivityOnRestart(this);//对应Activity的onRestart
            if (!mCalled) {
                throw new SuperNotCalledException(
                    "Activity " + mComponent.toShortString() +
                    " did not call through to super.onRestart()");
            }
            performStart();//----------------注意
        }
    }

3,performStart

final void performStart() {
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        mFragments.noteStateNotSaved();
        mCalled = false;
        mFragments.execPendingActions();
        mInstrumentation.callActivityOnStart(this);//对应Activity的onStart
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onStart()");
        }
        mFragments.dispatchStart();
        mFragments.reportLoaderStart();
        mActivityTransitionState.enterReady(this);
    }

NOTE:符合前面的onRestart->onStart->onResume

结论

onSaveInstanceState和onRestoreInstanceState并不是成对出现的,在后台的Activity有可能未被销毁,生命周期也是有区别的

你可能感兴趣的:(onSaveInstanceState)