Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android源碼解析之(十五)--)Activity銷毀流程

android源碼解析之(十五)--)Activity銷毀流程

編輯:關於Android編程

繼續我們的源碼解析,上一篇文章我們介紹了Activity的啟動流程,一個典型的場景就是Activity a 啟動了一個Activity b,他們的生命周期回調方法是:
onPause(a) –> onCreate(b) –> onStart(b) –> onResume(b) –> onStop(a)
而我們根據源碼也驗證了這樣的生命周期調用序列,那麼Activity的銷毀流程呢?它的生命周期的調用順序又是這樣的呢?

這裡我們我做一個簡單的demo,讓一個Activity a啟動Activity b,然後在b中調用finish()方法,它們的生命周期執行順序是:

onPause(b)
onRestart(a)
onStart(a)
onResume(a)
onStop(b)
onDestory(b)

好吧,根據我們測試的生命周期方法的回調過程開始對Activity銷毀流程的分析,一般而言當我們需要銷毀Activity的時候都會調用其自身的finish方法,所以我們的流程開始是以finish方法開始的。


一:請求銷毀當前Activity


MyActivity.finish()
Activity.finish()
ActivityManagerNative.getDefault().finishActivity()
ActivityManagerService.finishActivity()
ActivityStack.requestFinishActivityLocked()
ActivityStack.finishActivityLocked()
ActivityStack.startPausingLocked()

首先我們在自己的Activity調用了finish方法,它實際上調用的是Activity的finish方法:

public void finish() {
    finish(false);
}

然後我們可以發現其調用了finish方法的重載方法,並且傳遞了一個參數值:

private void finish(boolean finishTask) {
        if (mParent == null) {
            int resultCode;
            Intent resultData;
            synchronized (this) {
                resultCode = mResultCode;
                resultData = mResultData;
            }
            if (false) Log.v(TAG, "Finishing self: token=" + mToken);
            try {
                if (resultData != null) {
                    resultData.prepareToLeaveProcess();
                }
                if (ActivityManagerNative.getDefault()
                        .finishActivity(mToken, resultCode, resultData, finishTask)) {
                    mFinished = true;
                }
            } catch (RemoteException e) {
                // Empty
            }
        } else {
            mParent.finishFromChild(this);
        }
    }

好吧,這個參數值似乎並沒什麼用。。。這裡就不在討論了,然後調用了ActivityManagerNative.getDefault().finishActivity方法,好吧,根據上一篇文章的介紹,我們知道了ActivityManagerNative是一個Binder對象,這裡調用的方法最終會被ActivityManagerService執行,所以這了的finishActivity最終被執行的是ActivityManagerService.finishActivity方法,好吧,我們來看一下ActivityManagerService的finishActivity方法的執行邏輯。。。

@Override
public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, boolean finishTask) {
     ...
     res = tr.stack.requestFinishActivityLocked(token, resultCode,resultData, "app-request", true);
     ...
}

這裡我們可以發現,經過一系列邏輯判斷之後,最終調用了ActivityStack的requestFinishActivityLocked方法,這裡應該就是執行finish Activity的邏輯了。

final boolean requestFinishActivityLocked(IBinder token, int resultCode,
            Intent resultData, String reason, boolean oomAdj) {
        ActivityRecord r = isInStackLocked(token);
        if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(TAG_STATES,
                "Finishing activity token=" + token + " r="
                + ", result=" + resultCode + ", data=" + resultData
                + ", reason=" + reason);
        if (r == null) {
            return false;
        }

        finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
        return true;
    }

這個方法體裡面又調用了finishActivityLocked方法,那我們繼續看一下finishActivityLocked方法的實現:

final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
            String reason, boolean oomAdj) {
        ...
        startPausingLocked(false, false, false, false);
        ...
        return false;
    }

好吧,在這裡調用了startPausingLocked方法,看名字應該是開始要執行Activity的onPause方法請求了,然後我們看一下startPausingLocked方法的實現:

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming, boolean dontWait) {
       ...
            try {
                EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
                        prev.userId, System.identityHashCode(prev),
                        prev.shortComponentName);
                mService.updateUsageStats(prev, false);
                prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                        userLeaving, prev.configChangeFlags, dontWait);
            } catch (Exception e) {
                // Ignore exception, if process died other code will cleanup.
                Slog.w(TAG, "Exception thrown during pause", e);
                mPausingActivity = null;
                mLastPausedActivity = null;
                mLastNoHistoryActivity = null;
            }
        ...
    }

這樣從應用程序調用finish方法,ActivityManagerService接收請求並執行startPausingLocked方法。


二:執行當前Activity的onPause方法


IApplicationThread.schedulePauseActivity()
ActivityThread.schedulePauseActivity()
ActivityThread.sendMessage()
ActivityThread.H.sendMessage()
ActivityThread.H.handleMessage()
ActivityThread.handlePauseActivity()
ActivityThread.performPauseActivity()
Instrumentation.callActivityOnPause()
Activity.performPause()
Activity.onPause()
ActivityManagerNative.getDefault().activityPaused()
ActivityManagerService.activityPaused()
ActivityStack.activityPausedLocked()
ActivityStack.completePauseLocked()

在方法startPausingLocked中我們調用了:prev.app.thread.schedulePauseActivity這裡實際上調用的是IApplicationThread的schedulePauseActivity方法,IApplicationThread也是一個Binder對象,它是ActivityThread中ApplicationThread的Binder client端,所以最終會調用的是ApplicationThread的schedulePauseActivity方法,好吧我們看一下ActivityThread的schedulePauseActivity方法的具體實現:

public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) {
   sendMessage(
       finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
       token, (userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
                    configChanges);
}

然後調用了ActivityThread的sendMessage方法:

private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

然後又回調了sendMessage的重載方法。。

private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

最終調用mH發送異步消息,然後在mH的handleMessge方法中處理異步消息並調用handlePauseActivity方法:

private void handlePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges, boolean dontReport) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null) {
            //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
            if (userLeaving) {
                performUserLeavingActivity(r);
            }

            r.activity.mConfigChangeFlags |= configChanges;
            performPauseActivity(token, finished, r.isPreHoneycomb());

            // Make sure any pending writes are now committed.
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }

            // Tell the activity manager we have paused.
            if (!dontReport) {
                try {
                    ActivityManagerNative.getDefault().activityPaused(token);
                } catch (RemoteException ex) {
                }
            }
            mSomeActivitiesChanged = true;
        }
    }

好吧,這裡回調了performPauseActivity方法,上篇文章中我們已經分析過了這段代碼:

performPauseActivity()
Instrumentation.callActivityOnPause()
Activity.performPause()
Activity.onPause()

這樣我們就回調了第一個生命周期方法:onPause。。。

在handlePauseActivity方法中我們調用了ActivityManagerNative.getDefault().activityPaused(token)方法,好吧又是回調ActivityManagerService的方法,這樣最終會調用ActivityManagerService的activityPaused方法:

@Override
    public final void activityPaused(IBinder token) {
        final long origId = Binder.clearCallingIdentity();
        synchronized(this) {
            ActivityStack stack = ActivityRecord.getStackLocked(token);
            if (stack != null) {
                stack.activityPausedLocked(token, false);
            }
        }
        Binder.restoreCallingIdentity(origId);
    }

這樣,我們繼續看一下activityPausedLocked方法的實現:

final void activityPausedLocked(IBinder token, boolean timeout) {
        ...
        completePauseLocked(true);
        ...
}

裡面又經過一系列的邏輯判斷之後,開始執行completePauseLocked方法:

private void completePauseLocked(boolean resumeNext) {
    ...                   mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
    ...
    }

這樣棧頂Activity的onPause操作就執行完成了,接下來就就是開始執行上一個Activity的onResume操作了。。。

三:執行上一個Activity的onResume操作
這樣調用了ActivityStackSupervisor.resumeTopActivitiesLocked方法。。,又開始調用這個方法,通過上一篇文章的介紹,我們知道這個方法實際上是執行Activity的初始化,我們看一下其具體的調用過程:


ActivityStack.resumeTopActivityLocked()
ActivityStack.resumeTopInnerLocked()
IApplicationThread.scheduleResumeActivity()
ActivityThread.scheduleResumeActivity()
ActivityThread.sendMessage()
ActivityTherad.H.sendMessage()
ActivityThread.H.handleMessage()
ActivityThread.H.handleResumeMessage()
Activity.performResume()
Activity.performRestart()
Instrumentation.callActivityOnRestart()
Activity.onRestart()
Activity.performStart()
Instrumentation.callActivityOnStart()
Activity.onStart()
Instrumentation.callActivityOnResume()
Activity.onResume()

好吧,這個過程其實上一篇文章中已經做了介紹,這裡不做過多的分析了,通過這樣調用過程我們最終執行了當前棧頂Activity上一個Activity的onRestart方法,onStart方法,onResume方法等,下面我們將調用棧頂Activity的onStop方法,onDestory方法。

四:執行棧頂Activity的銷毀操作


Looper.myQueue().addIdleHandler(new Idler())
ActivityManagerNative.getDefault().activityIdle()
ActivityManagerService.activityIdle()
ActivityStackSupervisor.activityIdleInternalLocked()
ActivityStack.destroyActivityLocked()
IApplicationThread.scheduleDestoryActivity()
ActivityThread.scheduleDestoryActivity()
ActivityThread.sendMessage()
ActivityThread.H.sendMessage()
ActivityThread.H.handleMessage()
ActivityThread.handleDestoryActivity()
ActivityThread.performDestoryActivity()
Activity.performStop()
Instrumentation.callActivityOnStop()
Activity.onStop()
Instrumentation.callActivityOnDestory()
Activity.performDestory()
Acitivity.onDestory()
ActivityManagerNative.getDefault().activityDestoryed()
ActivityManagerService.activityDestoryed()
ActivityStack.activityDestoryedLocked()

我們在ActivityThread.handleResumeActivity方法中調用了Looper.myQueue().addIdleHandler(new Idler()),下面看一下這個方法的實現:

private class Idler implements MessageQueue.IdleHandler {
        @Override
        public final boolean queueIdle() {
            ActivityClientRecord a = mNewActivities;
            boolean stopProfiling = false;
            if (mBoundApplication != null && mProfiler.profileFd != null
                    && mProfiler.autoStopProfiler) {
                stopProfiling = true;
            }
            if (a != null) {
                mNewActivities = null;
                IActivityManager am = ActivityManagerNative.getDefault();
                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) {
                            // Ignore
                        }
                    }
                    prev = a;
                    a = a.nextIdle;
                    prev.nextIdle = null;
                } while (a != null);
            }
            if (stopProfiling) {
                mProfiler.stopProfiling();
            }
            ensureJitEnabled();
            return false;
        }
    }

內部有一個queueIdle的回調方法,當它被添加到MessageQueue之後就會回調該方法,我們可以發現在這個方法體中調用了ActivityManagerNative.getDefault.activityIdle方法,通過上一篇文章以及上面的講解,我們應該知道這了最終調用的是ActivityManagerService.activityIdle方法,好吧,這裡看一下activityIdle方法的具體實現:

@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, config);
                if (stopProfiling) {
                    if ((mProfileProc == r.app) && (mProfileFd != null)) {
                        try {
                            mProfileFd.close();
                        } catch (IOException e) {
                        }
                        clearProfilerLocked();
                    }
                }
            }
        }
        Binder.restoreCallingIdentity(origId);
    }

可以發現這裡又調用了ActivityStackSupervisor.activityIdleInternalLocked方法,然後我們看一下activityIdleInternalLocked方法的具體實現:

final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout, Configuration config) {
    ....   
    stack.destroyActivityLocked(r, true, "finish-idle");
    ....    
}

可以看到這裡調用ActivityStack.destroyActivityLocked方法,可以看一下其具體實現:

final boolean destroyActivityLocked(ActivityRecord r, boolean removeFromApp, String reason) {
      ...
      r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing, r.configChangeFlags);
      ...      
}

好吧,這裡又開始執行IApplicationThread.scheduleDestoryActivity方法,上文已經做了說明這裡最終調用的是ActivityThread.scheduleDestroyActivity方法,好吧,看一下ActivityThread.scheduleDestryActivity方法的實現:

public final void scheduleDestroyActivity(IBinder token, boolean finishing, int configChanges) {
    sendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
                    configChanges);
}

這裡有開始執行sendMessage方法,通過一系列的調用sendMessage方法最終調用了handleDestroyActivity方法:

private void handleDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance) {
        ActivityClientRecord r = performDestroyActivity(token, finishing,
                configChanges, getNonConfigInstance);
        if (r != null) {
            cleanUpPendingRemoveWindows(r);
            WindowManager wm = r.activity.getWindowManager();
            View v = r.activity.mDecor;
            if (v != null) {
                if (r.activity.mVisibleFromServer) {
                    mNumVisibleActivities--;
                }
                IBinder wtoken = v.getWindowToken();
                if (r.activity.mWindowAdded) {
                    if (r.onlyLocalRequest) {
                        // Hold off on removing this until the new activity's
                        // window is being added.
                        r.mPendingRemoveWindow = v;
                        r.mPendingRemoveWindowManager = wm;
                    } else {
                        wm.removeViewImmediate(v);
                    }
                }
                if (wtoken != null && r.mPendingRemoveWindow == null) {
                    WindowManagerGlobal.getInstance().closeAll(wtoken,
                            r.activity.getClass().getName(), "Activity");
                }
                r.activity.mDecor = null;
            }
            if (r.mPendingRemoveWindow == null) {
                // If we are delaying the removal of the activity window, then
                // we can't clean up all windows here.  Note that we can't do
                // so later either, which means any windows that aren't closed
                // by the app will leak.  Well we try to warning them a lot
                // about leaking windows, because that is a bug, so if they are
                // using this recreate facility then they get to live with leaks.
                WindowManagerGlobal.getInstance().closeAll(token,
                        r.activity.getClass().getName(), "Activity");
            }

            // Mocked out contexts won't be participating in the normal
            // process lifecycle, but if we're running with a proper
            // ApplicationContext we need to have it tear down things
            // cleanly.
            Context c = r.activity.getBaseContext();
            if (c instanceof ContextImpl) {
                ((ContextImpl) c).scheduleFinalCleanup(
                        r.activity.getClass().getName(), "Activity");
            }
        }
        if (finishing) {
            try {
                ActivityManagerNative.getDefault().activityDestroyed(token);
            } catch (RemoteException ex) {
                // If the system process has died, it's game over for everyone.
            }
        }
        mSomeActivitiesChanged = true;
    }

可以看到這裡調用了performDestroyActivity方法,用來執行Avtivity的onDestroy方法:

private ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance) {
       ...     
       r.activity.performStop();
       ...
       mInstrumentation.callActivityOnDestroy(r.activity);
       ...
    }

然後調用了Activity.performStop()方法,查看performStop方法:

final void performStop() {
        ...
        mInstrumentation.callActivityOnStop(this);
        ...
}

然後調用了Instrumentation.callActivityOnStop()方法:

public void callActivityOnStop(Activity activity) {
        activity.onStop();
    }

好吧,終於調用了Activity的onStop方法。。。

我們繼續看一下Instrumentation.callActivityOnDestroy()。。。。又是通過Instrumentation來調用Activity的onDestroy方法:

public void callActivityOnDestroy(Activity activity) {
    ...
    activity.performDestroy();
    ...
}

然後看一下Activity的performDestroy()方法的實現:

final void performDestroy() {
        mDestroyed = true;
        mWindow.destroy();
        mFragments.dispatchDestroy();
        onDestroy();
        mFragments.doLoaderDestroy();
        if (mVoiceInteractor != null) {
            mVoiceInteractor.detachActivity();
        }
    }

O(∩_∩)O哈哈~,終於回調了Activity的onDestroy方法。。。。


總結:

Activity的銷毀流程是從finish方法開始的

Activity銷毀過程是:onPause –> onRestart –> onStart –> onResume –> onStop –> onDestroy

Activity的銷毀流程是ActivityThread與ActivityManagerService相互配合銷毀的

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved