本文由文末多篇文章引导综合而成 源码更新于 AndroidCodeSearch (现在是 Android 11)

一、概述

AMSAT 相关部分,在 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);
// 【见 2.2】
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());
}
// 此时 requestCode = -1
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()) {
// 当该 monitor 阻塞 activity 启动,则直接返回
return requestCode >= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
// 【见 2.3】
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);
// 检查 activity 是否启动成功
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");
// 【见 2.3.1】
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.4】
}

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 {
// ...
// 执行启动 【见 2.5】
res = executeRequest(mRequest);
// ...
// activity 开始启动日志
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) {
//...
//收集 intent 所指向的 activity 信息
ActivityInfo aInfo = request.activityInfo;
//处理 intent 信息,当存在多个 activity 时,弹出 resolverAcitvity
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;
}
}

//...

// 获取调用者所在的 activity
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) {
// activity 执行结果的返回由源 activity 切换到新 activity,不需要返回结果则不会进该分支
// ...
}

if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
// 从 intent 中无法找到相应的 component
err = ActivityManager.START_INTENT_NOT_RESOLVED;
}

if (err == ActivityManager.START_SUCCESS && aInfo == null) {
// 从 intent 中无法找到相应的 ActivityInfo
err = ActivityManager.START_CLASS_NOT_FOUND;
}

if (err == ActivityManager.START_SUCCESS && sourceRecord != null
&& sourceRecord.getTask().voiceSession != null) {
// 启动的 activity 是 voice session 一部分
// ...
}

if (err == ActivityManager.START_SUCCESS && voiceSession != null) {
// 启动的是 voice session
// ...
}

final ActivityStack resultStack = resultRecord == null
? null : resultRecord.getRootTask();

//错误则返回
if (err != START_SUCCESS) {
return err;
}

// 检查权限
//...

// ActivityController 不为空的情况,比如 monkey 测试过程
if (mService.mController != null) {
//...
}

mInterceptor.setStates(userId, realCallingPid, realCallingUid, startFlags, callingPackage,
callingFeatureId);
if (mInterceptor.intercept(intent, rInfo, aInfo, resolvedType, inTask, callingPid,
callingUid, checkedOptions)) {
// activity 被拦截
//...
}
// 终止则返回
if (abort) {
//...
return START_ABORTED;
}

//...

// 创建 activity 记录对象
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)) {
// 如果前台 stack 还没有 resume 状态的 activity,则检查 app 是否允许切换
if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
realCallingPid, realCallingUid, "Activity start")) {
if (!(restrictedBgActivity && handleBackgroundActivityAbort(r))) {
// 如果不允许切换,则把要启动的 activity 添加到 PendingActivity,并且返回
mController.addPendingActivityLaunch(new PendingActivityLaunch(r,
sourceRecord, startFlags, stack, callerApp, intentGrants));
}
ActivityOptions.abort(checkedOptions);
return ActivityManager.START_SWITCHES_CANCELED;
}
}

mService.onStartActivitySetDidAppSwitch();
mController.doPendingActivityLaunches(false);
// 【见 2.6】
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, 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;
//...
//【见 2.7]】
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) {
//获取前台栈顶第一个非finishing的Activity
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isTopActivityFocusable()
|| (topTaskActivity != null && topTaskActivity.isTaskOverlay()
&& mStartActivity != topTaskActivity)) {
// 如果该活动是不可调焦的,我们不能恢复它,但仍然希望确保它在开始时可见(这也将触发进入动画)。
// 这方面的一个例子是PIP活动。
// 同样,我们不希望在一个任务中恢复当前有覆盖的活动,因为开始的活动只是需要在可见的暂停状态,直到覆盖被删除。
// 传递{@code null}作为start参数可以确保所有活动都是可见的。
mTargetStack.ensureActivitiesVisible(null /* starting */,0 /* configChanges */, !PRESERVE_WINDOWS);
// 继续并告诉窗口管理器为这个活动执行应用程序过渡,因为应用程序过渡不会通过 resume 通道触发。
mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
} else {
// 如果目标堆栈之前不是可调焦的 (该堆栈上之前的 top 运行活动不可见),
// 那么之前任何将该堆栈移动到该堆栈的调用都不会更新被调焦的堆栈。
// 如果现在启动新的活动允许任务堆栈可调焦,那么请确保我们现在相应地更新已调焦的堆栈。
if (mTargetStack.isTopActivityFocusable()
&& !mRootWindowContainer.isTopDisplayFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityInner");
}
// 【见 2.8】
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)) {
// 【见 2.9】 ActivityStack.resumeTopActivityUncheckedLocked
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) {
// 只需更新 targetStack 的结果,因为 targetStack 已经在上面恢复了。
// 我们不想再次恢复它,特别是在某些情况下,它会导致第二次启动失败,如果应用程序进程死亡。
resumedOnDisplay |= result;
continue;
}
if (taskDisplayArea.isTopStack(stack) && topRunningActivity.isState(RESUMED)) {
// 从 MoveTaskToFront 操作开始任何延迟的应用程序过渡,但只考虑显示的顶部任务和堆栈。
stack.executeAppTransition(targetOptions);
} else {
resumedOnDisplay |= topRunningActivity.makeActiveIfNeeded(target);
}
}
}
if (!resumedOnDisplay) {
// 在没有有效 activities 的情况下(例如,设备刚刚启动或启动程序崩溃),可能什么都没有恢复显示。
// 显式地请求集中堆栈中的top活动的resume将确保至少home活动被启动和恢复,并且不会发生递归。
final ActivityStack focusedStack = display.getFocusedStack();
if (focusedStack != null) {
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
} else if (targetStack == null) {
result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
display.getDefaultTaskDisplayArea());
}
}
}
return result;
}

mStackSupervisor 是一个 ActivityStackSupervisor 对象的实例。

  • ActivityStackSupervisor:负责所有 Activity 栈的管理。内部管理了 mRunningTasksmRecentTasks 两个 Activity 栈。其中, mRunningTasksHelper 类抽象出用于获取当前运行的任务集的逻辑; 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;
// 【见 2.10】
result = resumeTopActivityInnerLocked(prev, options);

// 当恢复 top 活动时,可能需要暂停 top 活动(例如,返回锁屏。
// 我们在 {@link #resumeTopActivityUncheckedLocked} 中取消了正常的暂停逻辑,因为顶部活动在结束时恢复。
// 我们在这里再次调用{@link ActivityStackSupervisor# checkreadyforsleepplocked}来确保任何必要的暂停逻辑发生。
// 在不考虑锁屏的情况下,活动将被显示,对{@link ActivityStackSupervisor# checkreadyforsleepplocked}的调用被跳过。
final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mInResumeTopActivity = false;
}

return result;
}

2.10 AStk.resumeTopActivityInnerLocked

这个方法比较长,主要负责上一个 activitypause 和下一个 activityresume 相关的一系列操作。

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) {

// 系统没有进入 booting 或 booted 状态,则不允许启动 Activity
if (!mAtmService.isBooting() && !mAtmService.isBooted()) {
return false;
}

// 找到第一个没有 finishing 的栈顶 activity
ActivityRecord next = topRunningActivity(true /* focusableOnly */);

final boolean hasRunningActivity = next != null;

// TODO: Maybe this entire condition can get removed?
if (hasRunningActivity && !isAttached()) {
return false;
}

// top running 之后的任意处于初始化状态且有显示 StartingWindow , 则移除 StartingWindow
mRootWindowContainer.cancelInitializingActivities();

// 暂停/恢复 处理情况,确保无论结束继续,状态都被重置。
boolean userLeaving = mStackSupervisor.mUserLeaving;
mStackSupervisor.mUserLeaving = false;

if (!hasRunningActivity) {
// 栈里没有 Activity 了,去别的地方看看。
return resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
}

//...

boolean pausing = taskDisplayArea.pauseBackStacks(userLeaving, next);
if (mResumedActivity != null) {
// onPause 【见 3.1】
pausing |= startPausingLocked(userLeaving, false /* uiSleeping */, next);
}

//...

try {
// ...
} catch (Exception e) {
// ...
// 【见 4.1】
mStackSupervisor.startSpecificActivity(next, true, false);
return true;
}

// ...
} else {
// ...
// 【见 4.1】
mStackSupervisor.startSpecificActivity(next, true, true);
}
return true;
}

resumeTopActivityInnerLocked() 方法中会去判断是否有 Activity 处于 Resume 状态。

如果有的话会先让这个 Activity 执行 Pausing 过程(其实也就是中 LauncheronPause 流程),然后再执行 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;

//...

// 把 prev 赋值给 mPausingActivity,这个值在 Activity 启动过程中会用到,
// 这边其实就是将 mResumedActivity 赋值给 mPausingActivity,就是我们的 Launcher(也可以叫未添加新 Activity 时的栈顶 Activity)。
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);
/*
* 从 Android P 开始,引入了 ClientLifecycleManager 和 ClientTransactionHandler 来辅助
* 管理 Activity 生命周期,它会发送 EXECUTE_TRANSACTION 消息到 ActivityThread.H 里面继续处理。
* 通过 ClientLifecycleManager 的 scheduleTransaction() 方法把 PauseActivityItem
* 事件加入到执行计划中,开始栈顶的 pausing 过程。
*
* ClientLifecycleManager getLifecycleManager() {
* return mLifecycleManager;
* }
*/
// 【见 3.2】 这里注意是 传递的是PauseActivityItem
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();
// 【见 3.3】
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 {
// 【见 3.4】
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 {
// 【见 3.5】
ActivityThread.this.scheduleTransaction(transaction);
}

3.5 CTH.scheduleTransaction

ActivityThread 类中并没有定义 scheduleTransaction() 方法,所以调用的是他父类 ClientTransactionHandlerscheduleTransaction() 方法。

1
2
3
4
5
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 【见 3.6】
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;
// Handler H 的实例接收到 EXECUTE_TRANSACTION 消息后调用
// TransactionExecutor.execute() 方法切换 Activity 状态。
// 【见 3.7】
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() executeLifecycleState() 6.1 会用到
// 处理添加的 callback 【见 3.8】
executeCallbacks(transaction);
// 处理 当前状态 设置的 LifecycleStateRequest 状态 之间的生命周期【见 6.1】
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);
//...
// 【见 3.9】 【见 5.2 和 7.6,由于步骤重复,省略了之前步骤】
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
//...
}
}

这里的 item2.11 重点强调了,调用 scheduleTransaction 时传递的是 PauseActivityItem ,所以这里调用的是 PauseActivityItem.execute

这里的 mTransactionHandlerActivityThread ,也就是下面的 client

3.9 PAI.execute

1
2
3
4
5
6
7
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
// 跳转到 ActivityThread.handlePauseActivity 方法 【见 3.10】
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() 方法
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;
// 【见 3.11】
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 方法 【见 3.12】
activity.performPause();
}

3.12 Aty.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();

mStackSupervisorActivityStack 父类 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;
// 如果 app 存在,并且已经启动
if (wpc != null && wpc.hasThread()) {
try {
// app 存在并且已经启动,调用 realStartActivityLocked() 方法 【见 5.1】
// andResume 在 2.10 中均是传递的 true
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {}
knownToBeDead = true;
}
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

final boolean isTop = andResume && r.isTopRunningActivity();
// 比如 Launcher 启动 app 的时候
// 调用 startProcessAsync() 方法启动新的进程 【见 4.2】
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}

mServiceActivityTaskManagerService

如果已经启动,就会调用 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);
}
// Message 包含一个 ActivityManagerInternal::startProcess 方法 【见 4.2.1】
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() 方法 【见 4.2.3】
startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
new HostingRecord(hostingType, hostingName, isTop),
ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
false /* isolated */, true /* keepIfLarge */);
}
} 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) {
// 【见 4.2.4】
return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
keepIfLarge, null /* ABI override */, null /* entryPoint */,
null /* entryPointArgs */, null /* crashHandler */);
}

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) {
//...
// 调用 startProcessLocked() 方法
final boolean success =
startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);
//...
}

final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
int zygotePolicyFlags, String abiOverride) {
// 调用 startProcessLocked() 方法
return startProcessLocked(app, hostingRecord, zygotePolicyFlags,
false /* disableHiddenApiChecks */, false /* disableTestApiChecks */,
false /* mountExtStorageFull */, abiOverride);
}

boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks,
boolean mountExtStorageFull, String abiOverride) {
//...

try {
//...
// 调用 startProcessLocked() 方法
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 {
// 调用 startProcess() 方法 【见 4.2.5】
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);

// We can't isolate app data and storage data as parent zygote already did that.
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,
/*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap,
false, false,
new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else {
// 执行 Process.start() 方法
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
Looper.prepareMainLooper();

// ...
// 初始化 ActivityThread
ActivityThread thread = new ActivityThread();
// attach 到系统进程 【见 4.2.7】
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 {
// 通过 ActivityManagerService 为这个应用绑定一个 Application 【见 4.2.8】
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// 添加一个垃圾回收观察者,每当系统触发垃圾回收的时候就会在 run 方法里面
// 去计算应用使用了多少内存,如果超过总量的四分之三就会尝试释放内存
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 {
// ...
}

//...

// 为根 View 添加 config 回调接收 config 变化相关的信息
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() 方法
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 {
// 调用 attachApplication() 方法 【见 4.2.9】
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 {
// 调用 RootWindowContainer.attachApplication() 方法 【见 4.2.10】
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; // Set to true if an activity was started.

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 /*starting*/) == STACK_VISIBILITY_INVISIBLE) {
break;
}
// RootWindowContainer::startActivityForAttachedApplicationIfNeeded 【见 4.2.11】
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 /* preserve_windows */);
}
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 {
// ActivityStackSupervisor.realStartActivityLocked 【见 5.1】
if (mStackSupervisor.realStartActivityLocked(r, app,
top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {
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 对象添加 LaunchActivityItem 的 callback
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;
// 设置当前的生命周期状态
// andResume 在 4.1 中传递为 true
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);

// 调用 ClientLifecycleManager.scheduleTransaction 方法
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);
// 调用 ActivityThread.handleLaunchActivity() 方法 【见 5.3】
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

3.1.8 分析到这里的 clientActivityThread 所以这里调用的是 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) {
//...
// 【见 5.4】
final Activity a = performLaunchActivity(r, customIntent);
//...
return a;
}

5.4 AT.performLaunchActivity

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
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 和 Activity
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//...
try {
// 初始化 Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
// ...
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
// 设置 Activity 的 Theme
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}

activity.mCalled = false;
if (r.isPersistable()) {
// 调用 Instrumentation.callActivityOnCreate() 方法 【见 5.5】
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);
// 调用 performCreate() 方法 【见 5.6】
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}

5.6 Aty.performCreate

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();
// 这里 r 表示 LaunchActivityItem , lifecycleItem 在 5.1 中所示为 ResumeActivityItem
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
}

public void cycleToPath(ActivityClientRecord r, int finish, ClientTransaction transaction) {
cycleToPath(r, finish, false /* excludeLastState */, transaction);
}

private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
ClientTransaction transaction) {
final int start = r.getLifecycleState();
// 计算需要执行那些生命周期 【见 6.2】
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
// 根据 【6.2】 返回执行生命周期 【见 6.3】
performLifecycleSequence(r, path, transaction);
}

6.2 TEH.getLifecyclePath

startON_CREATE = 1finishON_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) {// 3 > 1
if (start == ON_START && finish == ON_STOP) {
mLifecycleSequence.add(ON_STOP);
} else {
// 当前情况是走这里,mLifecycleSequence 添加了 2 和 3 也就是 ON_START 和 ON_RESUME
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
} else {
//...
}
//...
return mLifecycleSequence;
}

6.3 TE.performLifecycleSequence

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));
}
// 有 6.2 所知,这里状态 由 ON_START 到 ON_RESUME
// 所以会分别执行 mTransactionHandler.handleStartActivity 和 handleResumeActivity
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r.token, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, 0 /* configChanges */,
mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}

mTransactionHandler 如上是 ActivityThread ,所以最终能调用 ActivityThread.handleStartActivity

mTransactionHandler.handleStartActivityhandleResumeActivity 分别也是对应的 Activity 声明周期的 onStartonResume

七、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) {
//...
// onResume
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
//...
// 当 MessageQueue 空闲的时候就会执行这个 Handler,即执行完当前 Activity 的 onResume() 方法后执行
Looper.myQueue().addIdleHandler(new Idler());
}

7.2 Idler.queueIdle

IdleHandler 是一个回调接口,可以通过 MessageQueueaddIdleHandler 添加实现类。当 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;
// am 为 ActivityTaskManagerService
IActivityTaskManager am = ActivityTaskManager.getService();
ActivityClientRecord prev;
do {
if (a.activity != null && !a.activity.mFinished) {
try {
// 调用 ActivityTaskManagerService.activityIdle() 方法 【见 7.3】
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;
}
// 调用 ActivityStackSupervisor.activityIdleInternal 方法
mStackSupervisor.activityIdleInternal(r, false /* fromTimeout */,
false /* processPausingActivities */, 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) {
//...

// 暂停 和 结束 Activity 【见 7.5】
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<>();
}
// 添加需要 stop 的 activity
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);
// 熟悉的代码 之前 3.1 和 5.1 都调用过,这里传递的是 StopActivityItem
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 所需要的生命周期全部走完。

流程图

这个图画的煞费苦心 大图

AndroidActivity

感谢

因为 11 的资料太少,现在只能根据 10 的代码分析来分析 11 的逻辑。

两个版本只有部分不同,大部分代码逻辑都是相同的。

startActivity启动过程分析 仿照源码书写格式

【 Android 10 四大组件 】系列 – Activity 的 “启动流程”

深入理解Android 之 Activity启动流程(Android 10)

Android11中Activity的启动流程—从startActivity到onCreate