1.1 Activity的生命周期

Activity的生命周期

典型情况下的生命周期

正常情况下的Activity的生命周期

1.1 Activity的生命周期_第1张图片

  1. onCreate:表示Activity正在被创建,可以做初始化,比如setContentView加载界面,初始化Activity所需数据
  2. onRestart:表示Activity正在重新启动。当前Activity由不可见 变为 可见时,会调用onRestart。比如 按Home键,再回到该Activity
  3. onStart:表示Activity正在被启动。此时Activity可见,但是不在前台,此时用户不可见。
  4. onResume:表示Activity已经可见。在前台,可以与用户交互。
  5. onPause:表示Activity正在停止。可以做一些存储数据、停止动画的工作,但是不能太耗时,因为耗时会影响下一个Activity的显示。onPause执行完,才会执行新Activity的onResume
  6. onStop:表示Activity即将停止,可以做一些稍微重量级的回收工作,同样不能太耗时
  7. onDestory:表示Activity即将被销毁,可以做一些回收工作和最终的资源释放

以下几种情况,生命周期调用流程

  • 第一次启动一个Activity
12-07 18:00:49.356 9714-9714/? D/###MainActivity: onCreate::
12-07 18:00:49.364 9714-9714/? D/###MainActivity: onStart::
12-07 18:00:49.371 9714-9714/? D/###MainActivity: onResume::
  • 按Home键或锁屏
12-07 18:04:21.680 9714-9714/? D/###MainActivity: onPause::
12-07 18:04:22.023 9714-9714/? D/###MainActivity: onStop::
  • 再回到该Activity
12-07 18:04:47.222 9714-9714/? D/###MainActivity: onRestart::
12-07 18:04:47.240 9714-9714/? D/###MainActivity: onStart::
12-07 18:04:47.247 9714-9714/? D/###MainActivity: onResume::
  • 按back
12-07 18:06:18.822 9714-9714/? D/###MainActivity: onPause::
12-07 18:06:19.195 9714-9714/? D/###MainActivity: onStop::
12-07 18:06:19.195 9714-9714/? D/###MainActivity: onDestroy

onCreate和onDestory 标志着Activity的创建和销毁,只调用一次
onStart和onStop是针对Activity是否可见,伴随着用户按home键或 亮灭屏,多次被调用
onResume和onPause是针对Activity是否在前台,伴随着用户按home键或亮灭屏,多次被调用

通过源码看通过Activity A打开Activity B,先执行Activity A的onPause,再执行Activity B的onResume

12-07 18:20:51.326 25283-25283/? D/###MainActivity_A: onPause::
12-07 18:20:51.387 25283-25283/? D/###Activity_B: onCreate==
12-07 18:20:51.389 25283-25283/? D/###Activity_B: onStart==
12-07 18:20:51.391 25283-25283/? D/###Activity_B: onResume==
12-07 18:20:51.841 25283-25283/? D/###MainActivity_A: onStop::

ActivityStack.java

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
......
        // We need to start pausing the current activity so the top one
        // can be resumed...
        boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
        if (mResumedActivity != null) {
            if (DEBUG_STATES) Slog.d(TAG_STATES,
                    "resumeTopActivityLocked: Pausing " + mResumedActivity);
            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
        }
......

ActivityThread.java中 scheduleLaunchActivity 发送Message:LAUNCH_ACTIVITY——handleMessage中调用handleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
 // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        // Initialize before creating the activity
        WindowManagerGlobal.initialize();
        //创建Activity,会执行onCreate和onStart。
        //mInstrumentation.callActivityOnCreate,activity.performStart
        Activity a = performLaunchActivity(r, customIntent);

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            //调用Activity的onResume
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);

第一个Activity执行onPause后,才会执行第二个Activity的onResume,
所以不能在onPause中做重量级操作。onPause和onStop都不能做耗时操作,尤其是onPause。尽量在onStop中做操作,可以使新Activity尽快显示出来并切换到前台

异常情况下的生命周期切换

1.1 Activity的生命周期_第2张图片

异常情况下重建,如横竖屏切换

  • 情况1:资源相关的系统配置发生改变导致Activity被杀死并重新创建
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String test = "";
        //正常启动时,savedInstanceState为null
        if(null != savedInstanceState){
            test = savedInstanceState.getString("test");
        }
        Log.d(TAG, "onCreate:: test = " + test);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("test", "testString");
        Log.d(TAG, "onSaveInstanceState:: save test = testString");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        //onRestoreInstanceState被调用时,savedInstanceState不会为空
        String test = savedInstanceState.getString("test");
        Log.d(TAG, "onRestoreInstanceState:: test = " + test);
    }
  1. 竖屏 切横屏
12-08 10:25:49.397 13017-13017/? D/###MainActivity_A: onPause::
12-08 10:25:49.398 13017-13017/? D/###MainActivity_A: onSaveInstanceState:: save test = testString
12-08 10:25:49.399 13017-13017/? D/###MainActivity_A: onStop::
12-08 10:25:49.399 13017-13017/? D/###MainActivity_A: onDestroy::
12-08 10:25:49.467 13017-13017/? D/###MainActivity_A: onCreate:: test = testString
12-08 10:25:49.468 13017-13017/? D/###MainActivity_A: onStart::
12-08 10:25:49.468 13017-13017/? D/###MainActivity_A: onRestoreInstanceState:: test = testString
12-08 10:25:49.468 13017-13017/? D/###MainActivity_A: onResume::

2.横屏切竖屏

12-08 10:26:18.909 13017-13017/? D/###MainActivity_A: onPause::
12-08 10:26:18.909 13017-13017/? D/###MainActivity_A: onSaveInstanceState:: save test = testString
12-08 10:26:18.910 13017-13017/? D/###MainActivity_A: onStop::
12-08 10:26:18.910 13017-13017/? D/###MainActivity_A: onDestroy::
12-08 10:26:18.964 13017-13017/? D/###MainActivity_A: onCreate:: test = testString
12-08 10:26:18.965 13017-13017/? D/###MainActivity_A: onStart::
12-08 10:26:18.965 13017-13017/? D/###MainActivity_A: onRestoreInstanceState:: test = testString
12-08 10:26:18.966 13017-13017/? D/###MainActivity_A: onResume::

onSaveInstanceState在onStop之前调用,与onPause没有时序关系:onSaveInstanceState可以在onPause之前,也可以在onPause之后
onRestoreInstanceState在onStart之后
onSaveInstanceState将Activity当前的状态保存在Bundle中,onRestoreInstanceState和onCreate中的Bundle用来恢复数据

资源发生变化导致Activity被杀再重建,系统会帮我们做一些数据保存与恢复工作,比如EditText中用户输入的数据,ListView滚动的位置等。每个View也都有onSaveInstanceState和onRestoreInstanceState方法。

  • 保存和恢复View层次结构,系统流程:

    1. Activity会调用onSaveInstanceState保存数据
    2. Window保存数据
    3. Window上的顶层容器保存数据。顶层容器是一个ViewGroup,一般是DecorView
    4. 顶层容器的子元素保存数据

    如TextView的onSaveInstanceState保存了文本内容和文本选中状态

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();

        // Save state if we are forced to
        boolean save = mFreezesText;
        int start = 0;
        int end = 0;

        if (mText != null) {
            start = getSelectionStart();
            end = getSelectionEnd();
            if (start >= 0 || end >= 0) {
                // Or save state if there is a selection
                save = true;
            }
        }

        if (save) {
            SavedState ss = new SavedState(superState);
            // XXX Should also save the current scroll position!
            ss.selStart = start;
            ss.selEnd = end;

            if (mText instanceof Spanned) {
                Spannable sp = new SpannableStringBuilder(mText);

                if (mEditor != null) {
                    removeMisspelledSpans(sp);
                    sp.removeSpan(mEditor.mSuggestionRangeSpan);
                }

                ss.text = sp;
            } else {
                ss.text = mText.toString();
            }

            if (isFocused() && start >= 0 && end >= 0) {
                ss.frozenWithFocus = true;
            }

            ss.error = getError();

            if (mEditor != null) {
                ss.editorState = mEditor.saveInstanceState();
            }
            return ss;
        }

        return superState;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState ss = (SavedState)state;
        super.onRestoreInstanceState(ss.getSuperState());

        // XXX restore buffer type too, as well as lots of other stuff
        if (ss.text != null) {
            setText(ss.text);
        }

        if (ss.selStart >= 0 && ss.selEnd >= 0) {
            if (mText instanceof Spannable) {
                int len = mText.length();

                if (ss.selStart > len || ss.selEnd > len) {
                    String restored = "";

                    if (ss.text != null) {
                        restored = "(restored) ";
                    }

                    Log.e(LOG_TAG, "Saved cursor position " + ss.selStart +
                          "/" + ss.selEnd + " out of range for " + restored +
                          "text " + mText);
                } else {
                    Selection.setSelection((Spannable) mText, ss.selStart, ss.selEnd);

                    if (ss.frozenWithFocus) {
                        createEditorIfNeeded();
                        mEditor.mFrozenWithFocus = true;
                    }
                }
            }
        }

        if (ss.error != null) {
            final CharSequence error = ss.error;
            // Display the error later, after the first layout pass
            post(new Runnable() {
                public void run() {
                    if (mEditor == null || !mEditor.mErrorWasChanged) {
                        setError(error);
                    }
                }
            });
        }

        if (ss.editorState != null) {
            createEditorIfNeeded();
            mEditor.restoreInstanceState(ss.editorState);
        }
    }
  • 情况2:资源内存不足导致低优先级的Activity被杀死

Activity优先级:

  1. 前台Activity——正在和用户交互的Activity,优先级最高
  2. 可见但是 非前台的Activity——Activity中弹框,Activity可见 但是 不能和用户交互
  3. 后台Activity——已经被暂停的Activity,执行了onStop,优先级最低

    系统内存不足时,按照上边的顺序杀死目标Activity所在的进程,通过onSaveInstanceState和onRestoreInstanceState来保存和恢复数据。
    如果一个进程没有四大组件,这个进程很快就会被系统杀死


  • 屏幕旋转时防止Activity重建
    manifest中Activity添加configChanges属性
        <activity android:name=".MainActivity"
                android:configChanges="orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            intent-filter>
        activity>

横竖屏切换时,不会走onSaveInstanceState和onRestoreInstanceState,会调用onConfigurationChanged

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //ORIENTATION_PORTRAIT = 1是竖屏, ORIENTATION_LANDSCAPE = 2是横屏
        Log.d(TAG, "onConfigurationChanged:: orientation = " + newConfig.orientation);
    }

竖屏切横屏时,会打如下log

12-08 10:48:47.758 26593-26593/? D/###MainActivity_A: onConfigurationChanged:: orientation = 2

横屏切竖屏时,会打如下log
12-08 10:48:49.860 26593-26593/? D/###MainActivity_A: onConfigurationChanged:: orientation = 1

configChanges其他属性值
1.1 Activity的生命周期_第3张图片

你可能感兴趣的:(Android开发艺术探索)