Activity的onCreate中启动新的Activity时生命周期

05-26 00:19:22.680 3114-3114/com.lv.lifecycledemo E/MainActivity: onCreate
05-26 00:19:22.690 3114-3114/com.lv.lifecycledemo E/MainActivity: onStart
05-26 00:19:22.690 3114-3114/com.lv.lifecycledemo E/MainActivity: onResume
05-26 00:19:22.690 3114-3114/com.lv.lifecycledemo E/MainActivity: onPause
05-26 00:19:22.740 3114-3114/com.lv.lifecycledemo E/SecondActivity: onCreate
05-26 00:19:22.740 3114-3114/com.lv.lifecycledemo E/SecondActivity: onStart
05-26 00:19:22.740 3114-3114/com.lv.lifecycledemo E/SecondActivity: onResume
05-26 00:19:22.860 3114-3114/com.lv.lifecycledemo E/MainActivity: onSaveInstanceState
05-26 00:19:22.860 3114-3114/com.lv.lifecycledemo E/MainActivity: onStop

先完整走完第一个Activity的onCreate、onStart和onResume,onResume执行完之后发现不需要与用户进行交互(因为在onCreate中已经启动了一个新的Activity),就会执行第一个Activity的onPause方法。这段代码可以在ActivityThread的handleLaunchActivity方法中找到。

// ActivityThread
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        ...
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed);
        if (!r.activity.mFinished && r.startsNotResumed) {
            try {
                r.activity.mCalled = false;
                mInstrumentation.callActivityOnPause(r.activity);
            }
            ...
        }
        ...
    }
    ...
}

在第一个Activity暂停之后,就会执行第二个Activity的onCreate、onStart和onResume。这个时候,如果第二个Activity完全遮住了第一个,就会导致第一个Activity不可见,所以会接着调用第一个Activity的onSaveInstanceState和onStop方法。(因为第一个Activity不可见而变得容易被系统回收,所以会先调用一下onSaveInstanceState方法。)关于onSaveInstanceState的调用时机,Android官方文档有这么一句话。

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)

参考onSaveInstanceState和onRestoreInstanceState触发的时机

你可能感兴趣的:(Android)