通常而言當咱們須要銷燬Activity的時候都會調用其自身的finish方法,因此咱們的流程開始是以finish方法開始的。windows
一:請求銷燬當前Activityapp
MyActivity.finish()
Activity.finish()
ActivityManagerNative.getDefault().finishActivity()
ActivityManagerService.finishActivity()
ActivityStack.requestFinishActivityLocked()
ActivityStack.finishActivityLocked()
ActivityStack.startPausingLocked() 異步
首先咱們在本身的Activity調用了finish方法,它實際上調用的是Activity的finish方法:async
public void finish() { finish(false); }
而後咱們能夠發現其調用了finish方法的重載方法,而且傳遞了一個參數值:ide
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方法的執行邏輯。。。oop
@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的邏輯了。ui
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方法的實現:this
final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData, String reason, boolean oomAdj) { ... startPausingLocked(false, false, false, false); ... return false; }
好吧,在這裏調用了startPausingLocked方法,看名字應該是開始要執行Activity的onPause方法請求了,而後咱們看一下startPausingLocked方法的實現:spa
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方法。rest
二:執行當前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相互配合銷燬的