Activity啟動源碼分析(5)-- onStop,onDestroy探尋

前四篇的內容在這里。
Activity啟動源碼分析--總篇
Activity啟動源碼分析(1)--預啟動過程
Activity啟動源碼分析(2)--Pause過程
Activity啟動源碼分析(3)-- 新app進程創(chuàng)建過程
Activity啟動源碼分析(4)-- Activity B創(chuàng)建過程

1.目的

這個是這個啟動的最后一篇,講Activity生命周期里面回調的最后幾個方法。前面已經講到了onCreate,onStartonResume,onPause。還差onStop,onDestroy,onRestart??匆幌翧ctivity啟動過程中,他們究竟藏在哪里。
這篇結束后,Activity的幾個主要生命周期就都介紹了。當然,讀者也可以繼續(xù)拓展其他方法。
onStop還能算在這個啟動過程中,onDestroy,onRestart其實就沒多大關系了。下面會分開講。

2.OnStop

還是先放圖。

Stop過程

接著上篇,
ActivityThread

        public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ...
        //onResume執(zhí)行完后,會在空閑時執(zhí)行Idler
        Looper.myQueue().addIdleHandler(new Idler());
    }

IdleHandler是MessageQueue類里的一個借口,messages為空的時候就會執(zhí)行IdleHandler??聪?strong>Idler是怎么實現(xiàn)queueIdle()的。
ActivityThread

    private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ...
                mNewActivities = null;
                //這就相當眼熟了,我們直接往AMS去找
                IActivityManager am = ActivityManager.getService();
                ActivityClientRecord prev;
                do {
                    if (localLOGV) Slog.v(
                        TAG, "Reporting idle of " + a +
                        " finished=" +
                        (a.activity != null && a.activity.mFinished));
                    if (a.activity != null && !a.activity.mFinished) {
                        try {
                            am.activityIdle(a.token, a.createdConfig, stopProfiling);
                            a.createdConfig = null;
                        } catch (RemoteException ex) {
                            throw ex.rethrowFromSystemServer();
                        }
                    }
                    prev = a;
                    a = a.nextIdle;
                    prev.nextIdle = null;
                } while (a != null);
            }
            ...
            return false;
        }
    }

ActivityManagerService

    @Override
    public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
        final long origId = Binder.clearCallingIdentity();
        synchronized (this) {
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                ActivityRecord r =
                        mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
                                false /* processPausingActivities */, config);
                if (stopProfiling) {
                    if ((mProfileProc == r.app) && mProfilerInfo != null) {
                        clearProfilerLocked();
                    }
                }
            }
        }
        Binder.restoreCallingIdentity(origId);
    }

ActivityStackSupervisor

    @GuardedBy("mService")
    final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
            boolean processPausingActivities, Configuration config) {
        ...

        //找到當前不在界面上為Pause狀態(tài)的Activity
        // Atomically retrieve all of the other things to do.
        final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
                true /* remove */, processPausingActivities);
        NS = stops != null ? stops.size() : 0;
        if ((NF = mFinishingActivities.size()) > 0) {
            finishes = new ArrayList<>(mFinishingActivities);
            mFinishingActivities.clear();
        }

        if (mStartingUsers.size() > 0) {
            startingUsers = new ArrayList<>(mStartingUsers);
            mStartingUsers.clear();
        }

        // Stop any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NS; i++) {
            r = stops.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                //Pause的Activitiy正在finish狀態(tài),這里自然不是
                if (r.finishing) {
                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                            "activityIdleInternalLocked");
                } else {
                    //走你
                    stack.stopActivityLocked(r);
                }
            }
        }

        //onDestory會在這調用正在fininshing的Activity,是mFinishingActivities維護的。但是在前面沒有看到往mFinishingActivities添加成員的地方
        // Finish any activities that are scheduled to do so but have been
        // waiting for the next one to start.
        for (int i = 0; i < NF; i++) {
            r = finishes.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
            }
        }
        ...
    }

    final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
            boolean remove, boolean processPausingActivities) {
        ArrayList<ActivityRecord> stops = null;

        final boolean nowVisible = allResumedActivitiesVisible();
        for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
            ...
            if (remove) {
                final ActivityStack stack = s.getStack();
                final boolean shouldSleepOrShutDown = stack != null
                        ? stack.shouldSleepOrShutDownActivities()
                        : mService.isSleepingOrShuttingDownLocked();
                //非顯示狀態(tài)
                if (!waitingVisible || shouldSleepOrShutDown) {
                    //處于Pause
                    if (!processPausingActivities && s.isState(PAUSING)) {
                        // Defer processing pausing activities in this iteration and reschedule
                        // a delayed idle to reprocess it again
                        removeTimeoutsForActivityLocked(idleActivity);
                        scheduleIdleTimeoutLocked(idleActivity);
                        continue;
                    }

                    if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
                    if (stops == null) {
                        stops = new ArrayList<>();
                    }
                    //添加返回
                    stops.add(s);
                    mStoppingActivities.remove(activityNdx);
                }
            }
        }

        return stops;
    }

ActivityStack

    private boolean adjustFocusToNextFocusableStack(String reason, boolean allowFocusSelf) {
        final ActivityStack stack =
                mStackSupervisor.getNextFocusableStackLocked(this, !allowFocusSelf);
        final String myReason = reason + " adjustFocusToNextFocusableStack";
        if (stack == null) {
            return false;
        }

        final ActivityRecord top = stack.topRunningActivityLocked();

        if (stack.isActivityTypeHome() && (top == null || !top.visible)) {
            // If we will be focusing on the home stack next and its current top activity isn't
            // visible, then use the move the home stack task to top to make the activity visible.
            return mStackSupervisor.moveHomeStackTaskToTop(reason);
        }

        stack.moveToFront(myReason);
        return true;
    }

    final void stopActivityLocked(ActivityRecord r) {
        ...
                //再眼熟不過,讓ClientHandler去執(zhí)行StopActivityItem了。
                mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
                        StopActivityItem.obtain(r.visible, r.configChangeFlags));
        ...
    }

這里從LifecycleManagerApp傳遞的過程前面已描述兩次,這里不再贅述。
StopActivityItem

    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
        client.handleStopActivity(token, mShowWindow, mConfigChanges, pendingActions,
                true /* finalStateRequest */, "STOP_ACTIVITY_ITEM");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

ActivityThread

    @Override
    public void handleStopActivity(IBinder token, boolean show, int configChanges,
            PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
        ...
        performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
                reason);

        ...
    }

    private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
            boolean saveState, boolean finalStateRequest, String reason) {
        ...
            if (!keepShown) {
                callActivityOnStop(r, saveState, reason);
            }
        ...
    }

    private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
        // Before P onSaveInstanceState was called before onStop, starting with P it's
        // called after. Before Honeycomb state was always saved before onPause.
        final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
                && !r.isPreHoneycomb();
        final boolean isPreP = r.isPreP();
        if (shouldSaveState && isPreP) {
            callActivityOnSaveInstanceState(r);
        }

        try {
            //這里可以看到Stop方法的調用了
            r.activity.performStop(false /*preserveWindow*/, reason);
        } catch (SuperNotCalledException e) {
            throw e;
        } catch (Exception e) {
            if (!mInstrumentation.onException(r.activity, e)) {
                throw new RuntimeException(
                        "Unable to stop activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
            }
        }
        r.setState(ON_STOP);

        if (shouldSaveState && !isPreP) {
            callActivityOnSaveInstanceState(r);
        }
    }

可以從上面看到,onStop實在MessageQueue空閑才會調用。不像onPuase,onResume一定會被調用。

3.OnDestroy

從之前見到的方法里,唯一好像與onDestroy相關的。是ActivityStackSupervisor.mFinishingActivities。但是啟動流程里沒有見到正常賦值的地方啊,所以全局搜索一下,猜測一下是否有DestroyActivityItem這個類,果然是有的。再往回推調用鏈,可以看到正常調用有找到兩處,這里單列一下System_server端的調用關系:

對應App手動調用finish方法:
->ActivityManagerService:finishActivity
->ActivityStack:requestFinishActivityLocked
->ActivityStack:finishActivityLocked
->ActivityStack:finishCurrentActivityLocked
->ActivityStack:destroyActivityLocked

還有一個是

調用處可以參考第三篇Activity啟動源碼分析(3)-- 新app進程創(chuàng)建過程,在ActivityThread.attach有一個GcWatcher,內存占用大于3/4就會觸發(fā)
->ActivityManagerService:releaseSomeActivities
->ActivityStackSupervisor:releaseSomeActivitiesLocked
->ActivityStack:releaseSomeActivitiesLocked
->ActivityStack:destroyActivityLocked

這篇的話,有看過Pause過程的話,是相當容易理解的。因為這里調用方式都一致。不會有上一篇app進程創(chuàng)建過程設計過程那么復雜。當然,我的文章只能描述其中一部分,還有大部分需要讀者再從相關文章拓展。

其他地方看著都是異常時調用,還有系統(tǒng)強殺。所以onDestroy和onCreate一定會成對調用嗎?并不是的,onDestroy并不一定會被調用。正常的流程下,只有在調用了finish后3/4內存占用后觸發(fā)GC才調用了。所以反注冊一定需要很是小心。

推薦的一種寫法是

    @Override
    protected void onStop() {
        super.onStop();
        if(isFinishing()){
            //unRegister
        }
    }

3.OnRestart

在上一篇,我們有把cycleToPath具體分析。其實在這個里面
TransactionExecutorHelper

    public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
        ...
        //如果是從大的生命周期往小的生命周期變化,如onStop到onResume
        else { // finish < start, can't just cycle down
            if (start == ON_PAUSE && finish == ON_RESUME) {
                // Special case when we can just directly go to resumed state.
                mLifecycleSequence.add(ON_RESUME);
            } else if (start <= ON_STOP && finish >= ON_START) {
                // Restart and go to required state.

                //這里看到,最大也就是到onStop,并沒有調用onDestroy方法
                // Go to stopped state first.
                for (int i = start + 1; i <= ON_STOP; i++) {
                    mLifecycleSequence.add(i);
                }
                //然后調用了Restart
                // Restart
                mLifecycleSequence.add(ON_RESTART);
                // Go to required state
                for (int i = ON_START; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            } else {
                // Relaunch and go to required state

                // Go to destroyed state first.
                for (int i = start + 1; i <= ON_DESTROY; i++) {
                    mLifecycleSequence.add(i);
                }
                // Go to required state
                for (int i = ON_CREATE; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        }

        //移除了onResume
        // Remove last transition in case we want to perform it with some specific params.
        if (excludeLastState && mLifecycleSequence.size() != 0) {
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }

        return mLifecycleSequence;
    }

一言蔽之,就是onDestroy沒有調用的時候,Activity的狀態(tài)由大變小,就會走onRestart。

那生命周期都已經見到了,這六篇博客,著重從進程的關系,App的創(chuàng)建,Activity生命周期回調的幾個點,分析了Activity的啟動流程。當然,只是挑了一個比較關鍵的流程進行分析。若是從細節(jié)分析,如結合Task_Flag等,會有無窮盡的細節(jié)可以分析。這里只是幫讀者梳理一個可以切入分析的角度。有興趣的可以繼續(xù)深挖,學而有涯而識無涯,望于諸君砥礪前行。多謝各位~

參考文檔:

  1. (Android 9.0)Activity啟動流程源碼分析
  2. Android源碼解析之(十四)-->Activity啟動流程
  3. 從應用角度看Android源碼 - 是誰調用的ActivityThread的main方法
  4. https://developer.android.google.cn/guide/components/activities/activity-lifecycle
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容