本文由文末多篇文章引导综合而成 源码更新于 AndroidCodeSearch (现在是 Android 11)
一、概述
AMS 和 AT 相关部分,在 Service 启动分析 已经讲过了,startActivity的整体流程与 startService 非常相近,但比 Service 启动更为复杂,多了stack/task 以及 UI 的相关内容以及Activity的生命周期更为丰富。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| frameworks/base/services/core/java/com/android/server/am/ - ActivityManagerService.java (AMS) - ProcessList.java (PL)
frameworks/base/services/core/java/com/android/server/wm/ - ActivityTaskManagerService.java (ATMS) - ActivityStarter.java (AS) - RootWindowContainer.java (RWC) - ActivityStack.java (AStk) - ActivityRecord.java (AR) - ActivityStackSupervisor.java (ASS) frameworks/base/core/java/android/app/ - Activity.java (Aty) - Instrumentation.java (Ins) - ActivityTaskManager.java (ATM) - ClientTransactionHandler.java (CTH ActivityThread 父类) - ActivityManagerInternal.java (AMI)
- ActivityThread.java (AT 内含 ApplicationThread )
frameworks/base/core/java/android/app/servertransaction/ - ClientTransaction.java (CT) - TransactionExecutor.java (TE) - PauseActivityItem.java (PAI) - LaunchActivityItem.java (LAI) - TransactionExecutorHelper.java (TEH)
|
生成的文件和目录(Generated Files and Directories)
与上面重复的,发现从这里的文件时可以点击跳转目标方法,上面有的文件反而不行
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| out/soong/.intermediates/frameworks/base/framework-minus-apex/android_common/xref30/srcjars.xref/android/app/ - IApplicationThread.java (AIDL 文件生成的,内含 Proxy 和 Stub) - IActivityTaskManager.java (AIDL 文件生成的,内含 Proxy 和 Stub) - IActivityManager.java (AIDL 文件生成的,内含 Proxy 和 Stub) out/soong/.intermediates/frameworks/base/services/core/services.core.unboosted/android_common/xref/srcjars.xref/frameworks/base/services/core/java/com/android/server/wm/ - ActivityStartController.java (ASC) - ActivityStarter.java (AS) - RootWindowContainer.java (RWC) - ClientLifecycleManager.java (CLM) out/soong/.intermediates/frameworks/base/services/core/services.core.unboosted/android_common/xref/srcjars.xref/frameworks/base/services/core/java/com/android/server/am/ - ProcessList.java (PL)
|
话不多说,直接上源码
二、startActivity 源码
2.1 Aty.startActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| @Override public void startActivity(Intent intent) { this.startActivity(intent, null); }
@Override public void startActivity(Intent intent, @Nullable Bundle options) { if (options != null) { startActivityForResult(intent, -1, options); } else { startActivityForResult(intent, -1); } }
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { options = transferSpringboardActivityOptions(options); Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } if (requestCode >= 0) { mStartedActivity = true; }
cancelInputsAndStartExitTransition(options); } else { } }
|
execStartActivity() 方法的参数:
mMainThread: 数据类型为 ApplicationThread ,通过 mMainThread.getApplicationThread() 方法获取。
mToken: 数据类型为IBinder.
2.2 Ins.execStartActivity
这里可以发现实际操作的类是 Instrumentation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| @UnsupportedAppUsage public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); ActivityResult result = null; if (am.ignoreMatchingSpecificIntents()) { result = am.onStartActivity(intent); } if (result != null) { am.mHits++; return result; } else if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); int result = ActivityTaskManager.getService().startActivity(whoThread, who.getBasePackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }
|
2.2.1 ATM.getService (Client -> Service)
1 2 3 4 5 6 7 8 9 10 11 12 13
| public static IActivityTaskManager getService() { return IActivityTaskManagerSingleton.get(); }
@UnsupportedAppUsage(trackingBug = 129726065) private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() { @Override protected IActivityTaskManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } };
|
熟悉的代码,如果之前看过 Service 启动分析 对这段代码结构肯定不陌生,特别是 Singleton ,详细请看 Service 启动分析 2.3
这里用 AIDL 文件的特性,我们只需要找到谁继承了 IActivityTaskManager.Stub 。会发现是 ActivityTaskManagerService
2.3 ATMS.startActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Override public final int startActivity(IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); }
private int startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { assertPackageMatchesCallingUid(callingPackage); enforceNotIsolatedCaller("startActivityAsUser");
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser"); return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setCallingFeatureId(callingFeatureId) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setUserId(userId) .execute(); }
|
2.3.1 getActivityStartController().obtainStarter
1 2 3
| ActivityStarter obtainStarter(Intent intent, String reason) { return mFactory.obtain().setIntent(intent).setReason(reason); }
|
可以发现这里返回 ActivityStarter
2.4 AS.execute
这里不同版本代码会有很大的出入,
1 2 3 4 5 6 7 8 9 10 11 12 13
| int execute() { try { res = executeRequest(mRequest); mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(launchingState, res,mLastStartActivityRecord); return getExternalResult(mRequest.waitResult == null ? res : waitForResult(res, mLastStartActivityRecord)); } finally { } }
|
2.5 AS.executeRequest
这段有点长,但是中间只是用来做记录防止忘记,所以只写了注释省略了很多代码,重点在这个方法的最后。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| private int executeRequest(Request request) { ActivityInfo aInfo = request.activityInfo; ResolveInfo rInfo = request.resolveInfo;
WindowProcessController callerApp = null; if (caller != null) { callerApp = mService.getProcessController(caller); if (callerApp != null) { callingPid = callerApp.getPid(); callingUid = callerApp.mInfo.uid; } else { err = ActivityManager.START_PERMISSION_DENIED; } }
ActivityRecord sourceRecord = null; ActivityRecord resultRecord = null; if (resultTo != null) { sourceRecord = mRootWindowContainer.isInAnyStack(resultTo); if (sourceRecord != null) { if (requestCode >= 0 && !sourceRecord.finishing) { resultRecord = sourceRecord; } } }
final int launchFlags = intent.getFlags(); if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) { }
if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) { err = ActivityManager.START_INTENT_NOT_RESOLVED; }
if (err == ActivityManager.START_SUCCESS && aInfo == null) { err = ActivityManager.START_CLASS_NOT_FOUND; }
if (err == ActivityManager.START_SUCCESS && sourceRecord != null && sourceRecord.getTask().voiceSession != null) { }
if (err == ActivityManager.START_SUCCESS && voiceSession != null) { }
final ActivityStack resultStack = resultRecord == null ? null : resultRecord.getRootTask();
if (err != START_SUCCESS) { return err; }
if (mService.mController != null) { }
mInterceptor.setStates(userId, realCallingPid, realCallingUid, startFlags, callingPackage, callingFeatureId); if (mInterceptor.intercept(intent, rInfo, aInfo, resolvedType, inTask, callingPid, callingUid, checkedOptions)) { }
if (abort) { return START_ABORTED; }
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, callingPackage, callingFeatureId, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode, request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions, sourceRecord);
final ActivityStack stack = mRootWindowContainer.getTopDisplayFocusedStack();
if (voiceSession == null && stack != null && (stack.getResumedActivity() == null || stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) { if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, realCallingPid, realCallingUid, "Activity start")) { if (!(restrictedBgActivity && handleBackgroundActivityAbort(r))) { mController.addPendingActivityLaunch(new PendingActivityLaunch(r, sourceRecord, startFlags, stack, callerApp, intentGrants)); } ActivityOptions.abort(checkedOptions); return ActivityManager.START_SWITCHES_CANCELED; } }
mService.onStartActivitySetDidAppSwitch(); mController.doPendingActivityLaunches(false);
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true , checkedOptions, inTask, restrictedBgActivity, intentGrants);
if (request.outActivity != null) { request.outActivity[0] = mLastStartActivityRecord; }
return mLastStartActivityResult; }
|
2.6 AS.startActivityUnchecked
1 2 3 4 5 6 7 8 9 10 11 12
| private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { int result = START_CANCELED; result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants); return result; }
|
2.7 AS.startActivityInner
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) {
mTargetStack.startActivityLocked(mStartActivity, topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask, mKeepCurTransition, mOptions); if (mDoResume) { final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked(); if (!mTargetStack.isTopActivityFocusable() || (topTaskActivity != null && topTaskActivity.isTaskOverlay() && mStartActivity != topTaskActivity)) { mTargetStack.ensureActivitiesVisible(null ,0 , !PRESERVE_WINDOWS); mTargetStack.getDisplay().mDisplayContent.executeAppTransition(); } else { if (mTargetStack.isTopActivityFocusable() && !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) { mTargetStack.moveToFront("startActivityInner"); } mRootWindowContainer.resumeFocusedStacksTopActivities( mTargetStack, mStartActivity, mOptions); } }
return START_SUCCESS; }
|
2.8 RWC.resumeFocusedStacksTopActivities
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| boolean resumeFocusedStacksTopActivities( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!mStackSupervisor.readyToResume()) { return false; }
boolean result = false; if (targetStack != null && (targetStack.isTopStackInDisplayArea() || getTopDisplayFocusedStack() == targetStack)) { result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); }
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { final DisplayContent display = getChildAt(displayNdx); boolean resumedOnDisplay = false; for (int tdaNdx = display.getTaskDisplayAreaCount() - 1; tdaNdx >= 0; --tdaNdx) { final TaskDisplayArea taskDisplayArea = display.getTaskDisplayAreaAt(tdaNdx); for (int sNdx = taskDisplayArea.getStackCount() - 1; sNdx >= 0; --sNdx) { final ActivityStack stack = taskDisplayArea.getStackAt(sNdx); final ActivityRecord topRunningActivity = stack.topRunningActivity(); if (!stack.isFocusableAndVisible() || topRunningActivity == null) { continue; } if (stack == targetStack) { resumedOnDisplay |= result; continue; } if (taskDisplayArea.isTopStack(stack) && topRunningActivity.isState(RESUMED)) { stack.executeAppTransition(targetOptions); } else { resumedOnDisplay |= topRunningActivity.makeActiveIfNeeded(target); } } } if (!resumedOnDisplay) { final ActivityStack focusedStack = display.getFocusedStack(); if (focusedStack != null) { result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions); } else if (targetStack == null) { result |= resumeHomeActivity(null , "no-focusable-task", display.getDefaultTaskDisplayArea()); } } } return result; }
|
mStackSupervisor 是一个 ActivityStackSupervisor 对象的实例。
- ActivityStackSupervisor:负责所有
Activity 栈的管理。内部管理了 mRunningTasks 和 mRecentTasks 两个 Activity 栈。其中, mRunningTasks 是 Helper 类抽象出用于获取当前运行的任务集的逻辑; mRecentTasks 管理的是最近任务的历史列表,包括非活动任务。
2.9 AStk.resumeTopActivityUncheckedLocked
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) { if (mInResumeTopActivity) { return false; }
boolean result = false; try { mInResumeTopActivity = true; result = resumeTopActivityInnerLocked(prev, options);
final ActivityRecord next = topRunningActivity(true ); if (next == null || !next.canTurnScreenOn()) { checkReadyForSleep(); } } finally { mInResumeTopActivity = false; }
return result; }
|
2.10 AStk.resumeTopActivityInnerLocked
这个方法比较长,主要负责上一个 activity 的 pause 和下一个 activity 的 resume 相关的一系列操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) { if (!mAtmService.isBooting() && !mAtmService.isBooted()) { return false; }
ActivityRecord next = topRunningActivity(true );
final boolean hasRunningActivity = next != null;
if (hasRunningActivity && !isAttached()) { return false; }
mRootWindowContainer.cancelInitializingActivities();
boolean userLeaving = mStackSupervisor.mUserLeaving; mStackSupervisor.mUserLeaving = false;
if (!hasRunningActivity) { return resumeNextFocusableActivityWhenStackIsEmpty(prev, options); }
boolean pausing = taskDisplayArea.pauseBackStacks(userLeaving, next); if (mResumedActivity != null) { pausing |= startPausingLocked(userLeaving, false , next); }
try { } catch (Exception e) { mStackSupervisor.startSpecificActivity(next, true, false); return true; }
} else { mStackSupervisor.startSpecificActivity(next, true, true); } return true; }
|
在 resumeTopActivityInnerLocked() 方法中会去判断是否有 Activity 处于 Resume 状态。
如果有的话会先让这个 Activity 执行 Pausing 过程(其实也就是中 Launcher 的 onPause 流程),然后再执行 startSpecificActivity 方法来启动需要启动的 Activity。
三、onPause
3.1 AStk.startPausingLocked
栈顶 Activity 执行 onPause() 方法退出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, ActivityRecord resuming) { ActivityRecord prev = mResumedActivity;
mPausingActivity = prev; mLastPausedActivity = prev; mLastNoHistoryActivity = prev.isNoHistory() ? prev : null; prev.setState(PAUSING, "startPausingLocked"); prev.getTask().touchActiveTime(); clearLaunchTime(prev);
mAtmService.updateCpuStats();
if (prev.attachedToProcess()) { try { EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev), prev.shortComponentName, "userLeaving=" + userLeaving);
mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(), prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, prev.configChangeFlags, pauseImmediately)); } catch (Exception e) { mPausingActivity = null; mLastPausedActivity = null; mLastNoHistoryActivity = null; } } else { mPausingActivity = null; mLastPausedActivity = null; mLastNoHistoryActivity = null; }
}
|
3.2 CLM.scheduleTransaction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken, @NonNull ActivityLifecycleItem stateRequest) throws RemoteException { final ClientTransaction clientTransaction = transactionWithState(client, activityToken, stateRequest); scheduleTransaction(clientTransaction); }
void scheduleTransaction(ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); transaction.schedule(); if (!(client instanceof Binder)) { transaction.recycle(); } }
|
3.3 CT.schedule (Service -> Client)
1 2 3 4 5 6 7 8 9 10
| private IApplicationThread mClient;
public IApplicationThread getClient() { return mClient; }
public void schedule() throws RemoteException { mClient.scheduleTransaction(this); }
|
ClientTransaction.schedule() 方法的 mClient 是一个 IApplicationThread(这是一个 AIDL 文件生成的类) 类型,ActivityThread 的内部类 ApplicationThread 派生这个接口类并实现了对应的方法(这里不懂的看 2.2.1)。所以直接跳转到 ApplicationThread 中的 scheduleTransaction() 方法。
3.4 AT.scheduleTransaction
1 2 3 4 5
| @Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }
|
3.5 CTH.scheduleTransaction
ActivityThread 类中并没有定义 scheduleTransaction() 方法,所以调用的是他父类 ClientTransactionHandler 的 scheduleTransaction() 方法。
1 2 3 4 5
| void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
|
3.6 AT.H.handleMessage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class H extends Handler { public void handleMessage(Message msg) { switch (msg.what) { case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { transaction.recycle(); } break; } } }
|
3.7 TE.execute
1 2 3 4 5 6 7 8 9 10
| public void execute(ClientTransaction transaction) { final IBinder token = transaction.getActivityToken(); executeCallbacks(transaction);
executeLifecycleState(transaction); mPendingActions.clear(); }
|
3.8 TE.executeCallbacks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| ActivityThread.java private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
TransactionExecutor.java public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) { mTransactionHandler = clientTransactionHandler; }
public void executeCallbacks(ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); final int size = callbacks.size(); for (int i = 0; i < size; ++i) { final ClientTransactionItem item = callbacks.get(i); item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); } }
|
这里的 item 在 2.11 重点强调了,调用 scheduleTransaction 时传递的是 PauseActivityItem ,所以这里调用的是 PauseActivityItem.execute
这里的 mTransactionHandler 是 ActivityThread ,也就是下面的 client 。
3.9 PAI.execute
1 2 3 4 5 6 7
| @Override public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions, "PAUSE_ACTIVITY_ITEM"); }
|
3.10 AT.handlePauseActivity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| @Override public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, PendingTransactionActions pendingActions, String reason) { if (r != null) { performPauseActivity(r, finished, reason, pendingActions); } }
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason, PendingTransactionActions pendingActions) { performPauseActivityIfNeeded(r, reason); return shouldSaveState ? r.state : null; }
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) { try { r.activity.mCalled = false; mInstrumentation.callActivityOnPause(r.activity); if (!r.activity.mCalled) { throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent) + " did not call through to super.onPause()"); } } catch (SuperNotCalledException e) { throw e; } catch (Exception e) { if (!mInstrumentation.onException(r.activity, e)) { throw new RuntimeException("Unable to pause activity " + safeToComponentShortString(r.intent) + ": " + e.toString(), e); } } r.setState(ON_PAUSE); }
|
3.11 Ins.callActivityOnPause
这里可以发现实际操作 Activity 的类 还是 Instrumentation
1 2 3 4
| public void callActivityOnPause(Activity activity) { activity.performPause(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| final void performPause() { dispatchActivityPrePaused(); mDoReportFullyDrawn = false; mFragments.dispatchPause(); mCalled = false; onPause(); EventLogTags.writeWmOnPausedCalled(mIdent, getComponentName().getClassName(), "performPause"); mResumed = false; if (!mCalled && getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.GINGERBREAD) { throw new SuperNotCalledException( "Activity " + mComponent.toShortString() + " did not call through to super.onPause()"); } dispatchActivityPostPaused(); }
|
至此,Launcher 的 onPause() 流程分析结束!同时,我们需要明白一点:在启动一个 Activity 的时候最先被执行的是栈顶的 Activity 的 onPause() 方法。
四、新 Activity 的创建
4.1 ASS.startSpecificActivity
在 2.10 ActivityStack.resumeTopActivityInnerLocked 末尾,有一句 mStackSupervisor.startSpecificActivity();
mStackSupervisor 在 ActivityStack 父类 Task 中找到 final ActivityStackSupervisor mStackSupervisor; ,所以这里的 mStackSupervisor.startSpecificActivity 就是调用的 ActivityStackSupervisor 类的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public ActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) { mService = service; mLooper = looper; mHandler = new ActivityStackSupervisorHandler(looper); }
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) { final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid); boolean knownToBeDead = false; if (wpc != null && wpc.hasThread()) { try { realStartActivityLocked(r, wpc, andResume, checkConfig); return; } catch (RemoteException e) {} knownToBeDead = true; } r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
final boolean isTop = andResume && r.isTopRunningActivity(); mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity"); }
|
mService 是 ActivityTaskManagerService
如果已经启动,就会调用 realStartActivityLocked() 方法继续处理,注意 andResume 的值。
如果没有启动,则会调用 ActivityTaskManagerService.startProcessAsync() 方法创建新的进程,我们重点看下新应用进程的创建流程。
4.2 ATMS.startProcessAsync(新进程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop, String hostingType) { try { if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) { Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:" + activity.processName); } final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead, isTop, hostingType, activity.intent.getComponent()); mH.sendMessage(m); } finally { Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); } }
|
4.2.1 AMI.startProcess
1 2
| public abstract void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName);
|
一个抽象方法,由 ActivityManagerService 内部类 LocalService 实现
4.2.2 AMS.LocalService.startProcess
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public final class LocalService extends ActivityManagerInternal { @Override public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName) { try { if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:" + processName); } synchronized (ActivityManagerService.this) { startProcessLocked(processName, info, knownToBeDead, 0 , new HostingRecord(hostingType, hostingName, isTop), ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false , false , true ); } } finally { Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } } }
|
4.2.3 AMS.startProcessLocked
1 2 3 4 5 6 7 8 9 10 11 12
| final ProcessList mProcessList = new ProcessList();
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) { return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 , keepIfLarge, null , null , null , null ); }
|
4.2.4 PL.startProcessLocked
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { final boolean success = startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride); }
final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, int zygotePolicyFlags, String abiOverride) { return startProcessLocked(app, hostingRecord, zygotePolicyFlags, false , false , false , abiOverride); }
boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks, boolean mountExtStorageFull, String abiOverride) {
try { return startProcessLocked(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime); } catch (RuntimeException e) { mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false, false, true, false, false, app.userId, "start failure"); return false; } }
boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) {
if (mService.mConstants.FLAG_PROCESS_START_ASYNC) { mService.mProcStartHandler.post(() -> handleProcessStart( app, entryPoint, gids, runtimeFlags, zygotePolicyFlags, mountExternal, requiredAbi, instructionSet, invokeWith, startSeq)); return true; } else { try { final Process.ProcessStartResult startResult = startProcess(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime); handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper, startSeq, false); } catch (RuntimeException e) { app.pendingStart = false; mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false, false, true, false, false, app.userId, "start failure"); } return app.pid > 0; } }
|
4.2.5 PL.startProcess
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint, ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) { try { final Process.ProcessStartResult startResult; if (hostingRecord.usesWebviewZygote()) { startResult = startWebView(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges, new String[]{PROC_START_SEQ_IDENT + app.startSeq}); } else if (hostingRecord.usesAppZygote()) { final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
startResult = appZygote.getProcess().start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, null, app.info.packageName, ZYGOTE_POLICY_FLAG_EMPTY, isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap, false, false, new String[]{PROC_START_SEQ_IDENT + app.startSeq}); } else { startResult = Process.start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, app.info.packageName, zygotePolicyFlags, isTopApp, app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap, bindMountAppsData, bindMountAppStorageDirs, new String[]{PROC_START_SEQ_IDENT + app.startSeq}); } return startResult; } finally { Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } }
|
到这里,我们就明白了:ATMS.startProcessLocked() 方法经过多次跳转最终会通过 Process.start() 方法来为应用创建进程。
进程创建流程,请看 Android 进程创建流程
源码最后会执行到 ActivityThread.main() 方法,执行主线程的初始化工作。
4.2.6 AT.main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public static void main(String[] args) {
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq);
if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); }
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited"); }
|
4.2.7 AT.attach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| private void attach(boolean system, long startSeq) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } BinderInternal.addGcWatcher(new Runnable() { @Override public void run() { if (!mSomeActivitiesChanged) { return; } Runtime runtime = Runtime.getRuntime(); long dalvikMax = runtime.maxMemory(); long dalvikUsed = runtime.totalMemory() - runtime.freeMemory(); if (dalvikUsed > ((3*dalvikMax)/4)) { if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024) + " total=" + (runtime.totalMemory()/1024) + " used=" + (dalvikUsed/1024)); mSomeActivitiesChanged = false; try { ActivityTaskManager.getService().releaseSomeActivities(mAppThread); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } }); } else { }
ViewRootImpl.addConfigCallback(configChangedCallback); }
|
IActivityManager 的实现类是 ActivityManagerService ,可以查看谁继承了 IActivityManager.Stub 。
4.2.8 AMS.attachApplication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @Override public final void attachApplication(IApplicationThread thread, long startSeq) { if (thread == null) { throw new SecurityException("Invalid application interface"); } synchronized (this) { int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid, callingUid, startSeq); Binder.restoreCallingIdentity(origId); } }
public ActivityTaskManagerInternal mAtmInternal;
private boolean attachApplicationLocked(@NonNull IApplicationThread thread, int pid, int callingUid, long startSeq) {
if (normalMode) { try { didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } }
return true; }
|
ActivityTaskManagerInternal 的实现类是 ActivityTaskManagerService
4.2.9 ATMS.attachApplication
1 2 3 4 5 6 7 8
| public boolean attachApplication(WindowProcessController wpc) throws RemoteException { synchronized (mGlobalLockWithoutBoost) { try { return mRootWindowContainer.attachApplication(wpc); } finally {} } }
|
4.2.10 RWC.attachApplication
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| boolean attachApplication(WindowProcessController app) throws RemoteException { boolean didSomething = false; for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) { mTmpRemoteException = null; mTmpBoolean = false;
final DisplayContent display = getChildAt(displayNdx); for (int areaNdx = display.getTaskDisplayAreaCount() - 1; areaNdx >= 0; --areaNdx) { final TaskDisplayArea taskDisplayArea = display.getTaskDisplayAreaAt(areaNdx); for (int taskNdx = taskDisplayArea.getStackCount() - 1; taskNdx >= 0; --taskNdx) { final ActivityStack rootTask = taskDisplayArea.getStackAt(taskNdx); if (rootTask.getVisibility(null ) == STACK_VISIBILITY_INVISIBLE) { break; } final PooledFunction c = PooledLambda.obtainFunction( RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this, PooledLambda.__(ActivityRecord.class), app, rootTask.topRunningActivity()); rootTask.forAllActivities(c); c.recycle(); if (mTmpRemoteException != null) { throw mTmpRemoteException; } } } didSomething |= mTmpBoolean; } if (!didSomething) { ensureActivitiesVisible(null, 0, false ); } return didSomething; }
|
4.2.11 RWC.startActivityForAttachedApplicationIfNeeded
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r, WindowProcessController app, ActivityRecord top) { if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null || app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) { return false; }
try { if (mStackSupervisor.realStartActivityLocked(r, app, top == r && r.isFocusable() , true )) { mTmpBoolean = true; } } catch (RemoteException e) { Slog.w(TAG, "Exception in new application when starting activity " + top.intent.getComponent().flattenToShortString(), e); mTmpRemoteException = e; return true; } return false; }
|
五、onCreate
5.1 ASS.realStartActivityLocked
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException {
final Task task = r.getTask(); final ActivityStack stack = task.getStack(); beginDeferResume(); try { try { final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); final DisplayContent dc = r.getDisplay().mDisplayContent; clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), System.identityHashCode(r), r.info, mergedConfiguration.getGlobalConfiguration(), mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(), results, newIntents, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken, r.createFixedRotationAdjustmentsIfNeeded())); final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem);
mService.getLifecycleManager().scheduleTransaction(clientTransaction); } catch (RemoteException e) { } } finally { } return true; }
|
调用 ClientLifecycleManager.scheduleTransaction() 方法之后具体是如何执行 请看 [3.1 - 3.8](这里需要记住 3.7 有两个方法 executeCallbacks() executeLifecycleState() 6.1 会用到。之前传入的是 PauseActivityItem ,现在传入的是 LaunchActivityItem ,所以 item.execute 调用的是 LaunchActivityItem.execute() 方法。
5.2 LAI.execute
1 2 3 4 5 6 7 8 9
| public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments); client.handleLaunchActivity(r, pendingActions, null ); }
|
3.1.8 分析到这里的 client 是 ActivityThread 所以这里调用的是 ActivityThread.handleLaunchActivity()
5.3 AT.handleLaunchActivity
1 2 3 4 5 6 7 8 9
| @Override public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { final Activity a = performLaunchActivity(r, customIntent);
return a; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null) { r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); } ComponentName component = r.intent.getComponent(); if (component == null) { component = r.intent.resolveActivity( mInitialApplication.getPackageManager()); r.intent.setComponent(component); }
if (r.activityInfo.targetActivity != null) { component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity); } ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (activity != null) { CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); r.lastNonConfigurationInstances = null; checkAndBlockForNetworkAccess(); activity.mStartedActivity = false; int theme = r.activityInfo.getThemeResource(); if (theme != 0) { activity.setTheme(theme); }
activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } if (!activity.mCalled) { throw new SuperNotCalledException( "Activity " + r.intent.getComponent().toShortString() + " did not call through to super.onCreate()"); } r.activity = activity; mLastReportedWindowingMode.put(activity.getActivityToken(), config.windowConfiguration.getWindowingMode()); } r.setState(ON_CREATE);
synchronized (mResourcesManager) { mActivities.put(r.token, r); }
} catch (SuperNotCalledException e) { throw e;
} catch (Exception e) { }
return activity; }
|
5.5 Ins.callActivityOnCreate
1 2 3 4 5 6 7
| public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) { prePerformCreate(activity); activity.performCreate(icicle, persistentState); postPerformCreate(activity); }
|
1 2 3 4 5 6 7
| final void performCreate(Bundle icicle, PersistableBundle persistentState) { if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } }
|
至此 executeCallbacks() 执行完毕,开始执行 executeLifecycleState() 方法,会先执行 cycleToPath() 方法
六、onStart、onResume
6.1 TE.executeLifecycleState
3.7 executeCallbacks 执行完后开始执行 executeLifecycleState
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); cycleToPath(r, lifecycleItem.getTargetState(), true , transaction); }
public void cycleToPath(ActivityClientRecord r, int finish, ClientTransaction transaction) { cycleToPath(r, finish, false , transaction); }
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState, ClientTransaction transaction) { final int start = r.getLifecycleState(); final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState); performLifecycleSequence(r, path, transaction); }
|
6.2 TEH.getLifecyclePath
start 为 ON_CREATE = 1 ,finish 为 ON_RESUME = 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) { mLifecycleSequence.clear(); if (finish >= start) { if (start == ON_START && finish == ON_STOP) { mLifecycleSequence.add(ON_STOP); } else { for (int i = start + 1; i <= finish; i++) { mLifecycleSequence.add(i); } } } else { } return mLifecycleSequence; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| ActivityThread.java private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
TransactionExecutor.java public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) { mTransactionHandler = clientTransactionHandler; }
private void performLifecycleSequence(ActivityClientRecord r, IntArray path, ClientTransaction transaction) { final int size = path.size(); for (int i = 0, state; i < size; i++) { state = path.get(i); if (DEBUG_RESOLVER) { Slog.d(TAG, tId(transaction) + "Transitioning activity: " + getShortActivityName(r.token, mTransactionHandler) + " to state: " + getStateName(state)); } switch (state) { case ON_CREATE: mTransactionHandler.handleLaunchActivity(r, mPendingActions, null ); break; case ON_START: mTransactionHandler.handleStartActivity(r.token, mPendingActions); break; case ON_RESUME: mTransactionHandler.handleResumeActivity(r.token, false , r.isForward, "LIFECYCLER_RESUME_ACTIVITY"); break; case ON_PAUSE: mTransactionHandler.handlePauseActivity(r.token, false , false , 0 , mPendingActions, "LIFECYCLER_PAUSE_ACTIVITY"); break; case ON_STOP: mTransactionHandler.handleStopActivity(r.token, 0 , mPendingActions, false , "LIFECYCLER_STOP_ACTIVITY"); break; case ON_DESTROY: mTransactionHandler.handleDestroyActivity(r.token, false , 0 , false , "performLifecycleSequence. cycling to:" + path.get(size - 1)); break; case ON_RESTART: mTransactionHandler.performRestartActivity(r.token, false ); break; default: throw new IllegalArgumentException("Unexpected lifecycle state: " + state); } } }
|
mTransactionHandler 如上是 ActivityThread ,所以最终能调用 ActivityThread.handleStartActivity
mTransactionHandler.handleStartActivity 和 handleResumeActivity 分别也是对应的 Activity 声明周期的 onStart 和 onResume 。
七、onStop
7.1 AT.handleResumeActivity
为什么分析 onStop 要看 ActivityThread.handleResumeActivity 看代码就知道了。
1 2 3 4 5 6 7 8 9
| public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward, String reason) { final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason); Looper.myQueue().addIdleHandler(new Idler()); }
|
7.2 Idler.queueIdle
IdleHandler 是一个回调接口,可以通过 MessageQueue 的 addIdleHandler 添加实现类。当 MessageQueue 中的任务暂时处理完了(没有新任务或者下一个任务延时在之后),这个时候会回调这个接口,返回 false ,那么就会移除它,返回 true 就会在下次 message 处理完了的时候继续回调。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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; IActivityTaskManager am = ActivityTaskManager.getService(); ActivityClientRecord prev; do { 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); } if (stopProfiling) { mProfiler.stopProfiling(); } applyPendingProcessState(); return false; } }
|
7.3 ATMS.activityIdle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { final long origId = Binder.clearCallingIdentity(); try { synchronized (mGlobalLock) { Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "activityIdle"); final ActivityRecord r = ActivityRecord.forTokenLocked(token); if (r == null) { return; } mStackSupervisor.activityIdleInternal(r, false , false , config); if (stopProfiling && r.hasProcess()) { r.app.clearProfilerIfNeeded(); } } } finally { Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); Binder.restoreCallingIdentity(origId); } }
|
7.4 ASS.activityIdleInternal
1 2 3 4 5 6 7 8
| void activityIdleInternal(ActivityRecord r, boolean fromTimeout, boolean processPausingActivities, Configuration config) {
processStoppingAndFinishingActivities(r, processPausingActivities, "idle");
}
|
7.5 ASS.processStoppingAndFinishingActivities
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| private void processStoppingAndFinishingActivities(ActivityRecord launchedActivity, boolean processPausingActivities, String reason) { ArrayList<ActivityRecord> readyToStopActivities = null; for (int i = mStoppingActivities.size() - 1; i >= 0; --i) { final ActivityRecord s = mStoppingActivities.get(i); final boolean animating = s.isAnimating(TRANSITION | PARENTS, ANIMATION_TYPE_APP_TRANSITION | ANIMATION_TYPE_RECENTS); if (!animating || mService.mShuttingDown) { if (!processPausingActivities && s.isState(PAUSING)) { removeIdleTimeoutForActivity(launchedActivity); scheduleIdleTimeout(launchedActivity); continue; } if (readyToStopActivities == null) { readyToStopActivities = new ArrayList<>(); } readyToStopActivities.add(s);
mStoppingActivities.remove(i); } }
final int numReadyStops = readyToStopActivities == null ? 0 : readyToStopActivities.size(); for (int i = 0; i < numReadyStops; i++) { final ActivityRecord r = readyToStopActivities.get(i); if (r.isInHistory()) { if (r.finishing) { r.destroyIfPossible(reason); } else { r.stopIfPossible(); } } }
}
|
7.6 AR.stopIfPossible
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| void stopIfPossible() { try { EventLogTags.writeWmStopActivity( mUserId, System.identityHashCode(this), shortComponentName); mAtmService.getLifecycleManager().scheduleTransaction(app.getThread(), appToken, StopActivityItem.obtain(configChangeFlags));
if (stack.shouldSleepOrShutDownActivities()) { setSleeping(true); } mAtmService.mH.postDelayed(mStopTimeoutRunnable, STOP_TIMEOUT); } catch (Exception e) { } }
|
调用 ClientLifecycleManager.scheduleTransaction() 方法之后具体是如何执行 请看 [3.1 - 3.8] ,所以在 executeCallbacks() 方法中 item.execute 调用的是 StopActivityItem.execute() 方法。和 5.2 类似,具体代码就不贴了。
至此,启动一个 Activity 所需要的生命周期全部走完。
流程图
这个图画的煞费苦心 大图

感谢
因为 11 的资料太少,现在只能根据 10 的代码分析来分析 11 的逻辑。
两个版本只有部分不同,大部分代码逻辑都是相同的。
startActivity启动过程分析 仿照源码书写格式
【 Android 10 四大组件 】系列 – Activity 的 “启动流程”
深入理解Android 之 Activity启动流程(Android 10)
Android11中Activity的启动流程—从startActivity到onCreate