启动Activity过程

以Android 8.0版本为基础,以Launcher点击图标启动一个App来分析比较,这个过程需要很多次IPC,Launcher和AMS、AMS和App。
从IPC角度分析,启动流程大致为:

  1. Launcher与AMS进行IPC,通知AMS启动App;
  2. AMS做启动Activity之前的准备工作,Intent信息、LauncherMode、ActivityStack等完成后,AMS与Launcher进行IPC,通知Launcher进入后台;
  3. AMS检测目标Activity所在App进程是否存在,通知Zygote进程fork新进程;
  4. 新进程入口处ActivityThread.main()
  5. AMS通知App创建Application;
  6. AMS通知App创建Activity并回调相关生命周期
Launcher通知AMS启动App

Launcher本身就是一个应用,位于http://androidxref.com/8.0.0_r4/xref/packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
点击桌面上的应用图标,Launcher把启动所需要的信息放到Intent,调用startActivity(),这里假设启动App之前没有打开过App。

Activity.startActivityForResult

startActivity()多个重载方法最终均调用startActivityForResult(intent, requestCode, Bundle)。

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 void startActivity(Intent intent) {
this.startActivity(intent, null);
}

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) {
startActivityForResult(intent, requestCode, null);
}

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);
...
}
...
}

Instrumentation.execStartActivity

Activity的创建、启动和生命周期均由Instrumentation来完成。
看Instrumentation.execStartActivity()参数:
mMainThread:ActivityThread
mMainThread.getApplicationThread():ApplicationThread,ActivityThread内部类,是其他进程与App进程进行IPC的服务端。
mToken:IBinder类型,AMS端ActivityRecord.Token在App进程的本地Binder代理,具有跨进程代表Activity的能力(见Token)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token,
Activity target, Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
} catch (RemoteException e) {
}
return null;
}

ActivityManager

ActivityManager使用单例维护AMS本地代理。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};

ActivityManager.getService()返回am,am便是AMS的本地代理了(见Binder总结)。
App进程使用AMS本地代理调用startActivity(),经过Binder驱动最终调用SystemServer进程AMS.startActivity()

AMS.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
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho,
requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId());
}

public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId, true);
}

public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
enforceNotIsolatedCaller("startActivity");
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();

}

注意setMayWait(userId)这行代码,它把mayWait设置为true

AMS做启动Activity之前的准备工作,通知Launcher进入后台
ActivityStartController.obtainStarter
1
2
3
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}

mFactory:ActivityStarter内部类DefaultFactory,维护ActivityStarter对象池。

ActivityStarter.execute
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int execute() {
try {
//在前面AMS把mRequest.mayWait被设置为true。
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup);
}
}
}
ActivityStarter.startActivityMayWait

startActivityMayWait()主要寻找合适的待启动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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
private int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage,
Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration globalConfig,
SafeActivityOptions options, boolean ignoreTargetSecurity, int userId, TaskRecord inTask,
String reason, boolean allowPendingRemoteAnimationRegistryLookup) {
...
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
0, computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));
if (rInfo == null) {
UserInfo userInfo = mSupervisor.getUserInfo(userId);
if (userInfo != null && userInfo.isManagedProfile()) {
UserManager userManager = UserManager.get(mService.mContext);
boolean profileLockedAndParentUnlockingOrUnlocked = false;
long token = Binder.clearCallingIdentity();
try {
UserInfo parent = userManager.getProfileParent(userId);
profileLockedAndParentUnlockingOrUnlocked = (parent != null)
&& userManager.isUserUnlockingOrUnlocked(parent.id)
&& !userManager.isUserUnlockingOrUnlocked(userId);
} finally {
Binder.restoreCallingIdentity(token);
}
if (profileLockedAndParentUnlockingOrUnlocked) {
rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
computeResolveFilterUid(allingUid, realCallingUid, mRequest.filterCallingUid));
}
}
}
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

synchronized (mService) {
...
final ActivityRecord[] outRecord = new ActivityRecord[1];
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup);
...
return res;
}
}

ActivityStackSupervisor.resolveIntent

1
2
3
4
5
6
7
8
ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags, int filterCallingUid) {
synchronized (mService) {
...
return mService.getPackageManagerInternalLocked().resolveIntent(
intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);
...
}
}

mService.getPackageManagerInternalLocked()返回的是PMS。

PMS.resolveIntent

1
2
3
4
5
6
7
8
9
10
11
public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) {
return resolveIntentInternal(intent, resolvedType, flags, userId, false, Binder.getCallingUid());
}

private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
int flags, int userId, boolean resolveForStart, int filterCallingUid) {
...
final ResolveInfo bestChoice = chooseBestActivity(intent, resolvedType, flags, query, userId);
return bestChoice;
...
}

mSupervisor.resolveIntent()调用PMS处理存在多个符合Intent的Activity的情况,核心逻辑在chooseBestActivity()中。

  • 大于2个,返回ResolverActivity的ResolveInfo,弹出ResolverActivity,让用户选择启动哪个Activity,假如勾选了默认启动,下一次会直接启动默认配置的Activity;
  • 1个则直接返回。(通过ResolverActivity启动Activity调用的是AMS.startActivityAsCaller())

ActivityStackSupervisor.resolveActivity
主要做2件事:为Intent添加包名和类名;判断如果不是system进程则处理Debug,根据FLAG启动相应调试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags, ProfilerInfo profilerInfo) {
final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
if (aInfo != null) {
intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
if (!aInfo.processName.equals("system")) {
if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
mService.setDebugApp(aInfo.processName, true, false);
}
if ((startFlags & ActivityManager.START_FLAG_NATIVE_DEBUGGING) != 0) {
mService.setNativeDebuggingAppLocked(aInfo.applicationInfo, aInfo.processName);
}
if ((startFlags & ActivityManager.START_FLAG_TRACK_ALLOCATION) != 0) {
mService.setTrackAllocationApp(aInfo.applicationInfo, aInfo.processName);
}
if (profilerInfo != null) {
mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
}
}
}
return aInfo;
}

ActivityStarter.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
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
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, TaskRecord inTask, String reason,
boolean allowPendingRemoteAnimationRegistryLookup) {
...
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
inTask, allowPendingRemoteAnimationRegistryLookup);
...
return getExternalResult(mLastStartActivityResult);
}

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup){

//使用发起startActivity()进程的IApplicationThread本地代理查找保存在AMS的ProcessRecord
ProcessRecord callerApp = null;
if (caller != null) {
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
err = ActivityManager.START_PERMISSION_DENIED;
}
}
...
//使用发起startActivity()的Activity的Token去查找保存在AMS的ActivityRecord
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
sourceRecord = mSupervisor.isInAnyStackLocked(resultTo);
if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
"Will send result to " + resultTo + " " + sourceRecord);
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
//判断非法参数、启动权限等
...
//构造ActivityRecord,并把ProcessRecord和ActivityRecord等放进新构造的ActivityRecord中,后面的方法均使用ActivityRecord
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
mSupervisor, checkedOptions, sourceRecord);
...
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
...
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
...
return result;
}

使用调用者的IApplicationThreadToken去AMS分别查找到对应的ProcessRecordActivityRecord,放到新构造的ActivityRecord中。
ProcessRecord:保存App中某一个进程的全部信息。包括当前进程的IApplicationThread的本地引用。
ActivityRecord:保存App中某一个进程的某一个Activity的全部信息。包括AMS的ActivityRecord用来跨进程标记对应Activity的Binder对象Token。
ProcessRecord和ActivityRecord均保存在AMS中,客户度可通过当前进程的ApplicationThread去AMS获取ProcessRecord,用ActivityRecord.Token获取ActivityRecord;同样的,客户端同样会保存一份ActivityClientRecord列表,ActivityClientRecord保存着AMS传来的Token的本地代理,AMS借助Token便可以在客户端ActivithThread查找指定的ActivityClientRecord并操作相应的Activity。这样通过2个BinderApp和AMS映射成功。

ActivityStarter.startActivityUnchecked
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) {
//初始化一些值。doResume的值是true。
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
//处理LauncherMode
computeLaunchingTaskFlags();
//处理ActivityStack
computeSourceStack();
//给Intent设置LauncherMode
mIntent.setFlags(mLaunchFlags);
//去ActivityStack寻找可重复使用的ActivityRecord,查找Activity是否在栈中,然后处理LaunchMode
ActivityRecord reusedActivity = getReusableIntentActivity();
...
if (reusedActivity != null) {
if (mService.getLockTaskController().isLockTaskModeViolation(reusedActivity.getTask(),
(mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
== (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {
return START_RETURN_LOCK_TASK_MODE_VIOLATION;
}

final boolean clearTopAndResetStandardLaunchMode =
(mLaunchFlags & (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED))
== (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
&& mLaunchMode == LAUNCH_MULTIPLE;

if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) {
mStartActivity.setTask(reusedActivity.getTask());
}

if (reusedActivity.getTask().intent == null) {
reusedActivity.getTask().setIntent(mStartActivity);
}

if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
|| isDocumentLaunchesIntoExisting(mLaunchFlags)
|| isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
final TaskRecord task = reusedActivity.getTask();

final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
mLaunchFlags);

if (reusedActivity.getTask() == null) {
reusedActivity.setTask(task);
}

if (top != null) {
if (top.frontOfTask) {
top.getTask().setIntent(mStartActivity);
}
//回调onNewIntent()
deliverNewIntent(top);
}
}

mSupervisor.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */, reusedActivity);

reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);

final ActivityRecord outResult =
outActivity != null && outActivity.length > 0 ? outActivity[0] : null;

if (outResult != null && (outResult.finishing || outResult.noDisplay)) {
outActivity[0] = reusedActivity;
}

if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
resumeTargetStackIfNeeded();
return START_RETURN_INTENT_TO_CALLER;
}

if (reusedActivity != null) {
setTaskFromIntentActivity(reusedActivity);

if (!mAddingToTask && mReuseTask == null) {
resumeTargetStackIfNeeded();
if (outActivity != null && outActivity.length > 0) {
outActivity[0] = reusedActivity;
}
return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;
}
}
}
//判断包名
if (mStartActivity.packageName == null) {
final ActivityStack sourceStack = mStartActivity.resultTo != null
? mStartActivity.resultTo.getStack() : null;
if (sourceStack != null) {
sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,
mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,null /* data */);
}
ActivityOptions.abort(mOptions);
return START_CLASS_NOT_FOUND;
}
//待启动Activity正好在栈顶时,处理 SINGLE_TOP 的情况
final ActivityStack topStack = mSupervisor.mFocusedStack;
final ActivityRecord topFocused = topStack.getTopActivity();
final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
final boolean dontStart = top != null && mStartActivity.resultTo == null
&& top.realActivity.equals(mStartActivity.realActivity)
&& top.userId == mStartActivity.userId
&& top.app != null && top.app.thread != null
&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
|| isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));
if (dontStart) {
topStack.mLastPausedActivity = null;
if (mDoResume) {
mSupervisor.resumeFocusedStackTopActivityLocked();
}
ActivityOptions.abort(mOptions);
if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
return START_RETURN_INTENT_TO_CALLER;
}
//回调onNewIntent()
deliverNewIntent(top);
mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(), preferredWindowingMode,
preferredLaunchDisplayId, topStack);
return START_DELIVERED_TO_TOP;
}

boolean newTask = false;
final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;

//处理需要创建新栈的情况
int result = START_SUCCESS;
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
} else if (mSourceRecord != null) {
result = setTaskFromSourceRecord();
} else if (mInTask != null) {
result = setTaskFromInTask();
} else {
setTaskToCurrentTopOrCreateNewTask();
}
if (result != START_SUCCESS) {
return result;
}
...
//处理TaskRecord,并用Token创建AppWindowToken绑定到DisplayContent待WMS使用。
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);
//mDoResume在setInitialState()被设置为true
if (mDoResume) {
final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable() || (topTaskActivity != null &&
topTaskActivity.mTaskOverlay && mStartActivity != topTaskActivity)) {
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
mService.mWindowManager.executeAppTransition();
} else {
if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
//最终会指定到这里。
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
}
} else if (mStartActivity != null) {
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
}
...
return START_SUCCESS;
}

主要做了Task相关的事情,根据LaunchMode和LaunchFlags处理Task。正常启动会调用mSupervisor.resumeFocusedStackTopActivityLocked()

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
//ActivityStackSupervisor
boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions){
//判断重复启动,在realStartActivityLocked()被设置
if (!readyToResume()) {
return false;
}
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
...
return false;
}

//ActivityStack
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
//判断重复启动
if (mStackSupervisor.inResumeTopActivity) { return false;}
boolean result = false;
try {
mStackSupervisor.inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
...
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}

ActivityStack.resumeTopActivityInnerLocked
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//AMS没有处于启动中或启动完成,不往下执行
if (!mService.mBooting && !mService.mBooted) {
return false;
}
//查找栈中下一个最上面的准备Activity
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
final boolean hasRunningActivity = next != null;
//如果没有设置ActivityDisplay,不往下执行
if (hasRunningActivity && !isAttached()) {
return false;
}
//如果栈顶Activity下面有处于初始化状态且StartWindow正在显示的Activity,则移除StartWindow。
mStackSupervisor.cancelInitializingActivities();

boolean userLeaving = mStackSupervisor.mUserLeaving;
mStackSupervisor.mUserLeaving = false;

if (!hasRunningActivity) {
//当前栈没有找到未停止且有焦点的ActivityRecord,则寻找其他栈。
//这个方法会调用resumeFocusedStackTopActivityLocked()方法,直到找不到时会启动桌面Activity。
return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities");
}
next.delayedResume = false;
//如果栈顶Activity就是目标Activity且是resumed状态,直接返回不往下执行
if (mResumedActivity == next && next.isState(RESUMED)
&& mStackSupervisor.allResumedActivitiesComplete()) {
executeAppTransition(options);
return false;
}

//系统处于睡眠或关机状态,且栈顶Activity处于暂停状态,不往下执行
if (shouldSleepOrShutDownActivities() && mLastPausedActivity == next
&& mStackSupervisor.allPausedActivitiesComplete()) {
executeAppTransition(options);
return false;
}

//拥有该Activity的用户如果没有启动,不往下执行
if (!mService.mUserController.hasStartedUserState(next.userId)) {
return false;
}
//把ActivityRecord从3个列表中移除
mStackSupervisor.mStoppingActivities.remove(next);
mStackSupervisor.mGoingToSleepActivities.remove(next);
next.sleeping = false;
mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(next);

//再次确认所有的Activity是否完成Paused状态
if (!mStackSupervisor.allPausedActivitiesComplete()) {
return false;
}
mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);

//PIP(画中画)设置
boolean lastResumedCanPip = false;
ActivityRecord lastResumed = null;
final ActivityStack lastFocusedStack = mStackSupervisor.getLastStack();
if (lastFocusedStack != null && lastFocusedStack != this) {
lastResumed = lastFocusedStack.mResumedActivity;
if (userLeaving && inMultiWindowMode() && lastFocusedStack.shouldBeVisible(next)) {
userLeaving = false;
}
lastResumedCanPip = lastResumed != null && lastResumed.checkEnterPictureInPictureState(
"resumeTopActivity", userLeaving /* beforeStopping */);
}
final boolean resumeWhilePausing = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0
&& !lastResumedCanPip;

//暂停所有Activity栈中的所有Activity(均调用startPausingLocked()暂停Activity)
boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
if (mResumedActivity != null) {
//开始暂停当前栈中resumed状态的Activity,通常是启动Activity的那个Activity
pausing |= startPausingLocked(userLeaving, false, next, false);
}
if (pausing && !resumeWhilePausing) {
if (next.app != null && next.app.thread != null) {
//调整进程在AMS的mLruProcesses列表中的位置
mService.updateLruProcessLocked(next.app, true, null);
}
if (lastResumed != null) {
lastResumed.setWillCloseOrEnterPip(true);
}
return true;
} else if (mResumedActivity == next && next.isState(RESUMED)
&& mStackSupervisor.allResumedActivitiesComplete()) {
executeAppTransition(options);
return true;
}

//设备处于即将休眠的状态,关闭设置LaunchMode和LauncherFlag为NO_HISTORY标记且已暂停但未停止的Activity,
if (shouldSleepActivities() && mLastNoHistoryActivity != null && !mLastNoHistoryActivity.finishing){
requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
null, "resume-no-history", false);
mLastNoHistoryActivity = null;
}

...

mStackSupervisor.mNoAnimActivities.clear();
ActivityStack lastStack = mStackSupervisor.getLastStack();
//如果待启动Activity的进程信息存在
if (next.app != null && next.app.thread != null) {
final boolean lastActivityTranslucent = lastStack != null
&& (lastStack.inMultiWindowMode()
|| (lastStack.mLastPausedActivity != null
&& !lastStack.mLastPausedActivity.fullscreen));

synchronized(mWindowManager.getWindowManagerLock()) {
//把Activity设置为可见
if (!next.visible || next.stopped || lastActivityTranslucent) {
next.setVisibility(true);
}

next.startLaunchTickingLocked();
ActivityRecord lastResumedActivity =
lastStack == null ? null :lastStack.mResumedActivity;
final ActivityState lastState = next.getState();
mService.updateCpuStats();

//设置Activity的状态为resume
next.setState(RESUMED, "resumeTopActivityInnerLocked");

mService.updateLruProcessLocked(next.app, true, null);
updateLRUListLocked(next);
mService.updateOomAdjLocked();
boolean notUpdated = true;

if (mStackSupervisor.isFocusedStack(this)) {
notUpdated = !mStackSupervisor.ensureVisibilityAndConfig(next, mDisplayId,
true /* markFrozenIfConfigChanged */, false /* deferResume */);
}
if (notUpdated) {
ActivityRecord nextNext = topRunningActivityLocked();
if (nextNext != next) {
mStackSupervisor.scheduleResumeTopActivities();
}
if (!next.visible || next.stopped) {
next.setVisibility(true);
}
next.completeResumeLocked();
return true;
}

try {
final ClientTransaction transaction = ClientTransaction.obtain(next.app.thread,
next.appToken);
ArrayList<ResultInfo> a = next.results;
if (a != null) {
final int N = a.size();
if (!next.finishing && N > 0) {
//回调Activity.onActivityResult()
transaction.addCallback(ActivityResultItem.obtain(a));
}
}
//回调Activity.onNewIntent()
if (next.newIntents != null) {
transaction.addCallback(NewIntentItem.obtain(next.newIntents,false /* andPause */));
}
next.notifyAppResumed(next.stopped);
next.sleeping = false;
mService.getAppWarningsLocked().onResumeActivity(next);
mService.showAskCompatModeDialogLocked(next);
next.app.pendingUiClean = true;
next.app.forceProcessStateUpTo(mService.mTopProcessState);
next.clearOptionsLocked();
//回调Activity.onResume()
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.repProcState,mService.isNextTransitionForward()));
mService.getLifecycleManager().scheduleTransaction(transaction);
} catch (Exception e) {
...
//发生异常启动Activity
mStackSupervisor.startSpecificActivityLocked(next, true, false);
return true;
}
}
...
}
//App第一次被启动或者创建新进程的状态
else {
...
//启动Activity
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
return true;
}
通知Launcher进入后台
1
2
3
4
5
6
7
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
if (mResumedActivity != null) {
pausing |= startPausingLocked(userLeaving, false, next, false);
}
...
}

调用startPausingLocked()处理上一个Activity也就是Launcher的暂停工作。
(点击查看)

ActivityStackSupervisor.startSpecificActivityLocked
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig){
//判断待启动Activity的在AMS保存的进程信息,如果没有则代表进程未创建
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
getLaunchTimeTracker().setLaunchTime(r);
if (app != null && app.thread != null) {
try {
...
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
}
}
//创建Activity所在进程。
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}

判断待启动Activity所在进程是否存在,如果存在则调用realStartActivityLocked()执行创建Activity的流程;如果进程还未创建,则首先创建新进程。
Launcher点击启动App,假设App为启动过,所以需要创建新进程

AMS通知Zygote创建新进程

Socket通信:

服务端ServerSocket:

  • 创建服务端ServerSocket并绑定端口;
  • 通过调用accept()监听客户端请求;
  • 建立连接后返回连接的Socket;
  • 通过Socket的输入流读取客户端发送的请求信息,通过输出流向客户端发送响应信息;
  • 关闭Socket及响应资源。
    客户端Socket:
  • 创建客户端Socket并设置连接的IP和端口;
  • 建立连接后通过输入流向服务端请求信息,通过输出流读取服务端响应信息;
  • 关闭Socket及响应资源。

SystemServer进程和Zygote进程:

  • LocalSocketAddress:一个UNIX域的Socket地址,用于创建LocalSocket或LocalServerSocket,相当于IP及端口号;
  • LocalSocket:在Unix域命名空间中创建(非服务器)Socket。此类及其返回的流支持多线程,相当于客户端Socket,由AMS创建;
  • LocalServerSocket:用于在Linux抽象命名空间中创建入站UNIX域套接字的非标准类。相当于服务端Socket,由Zygote创建;
  • LocalSocketImpl:完成调用native层Socket代码;
AMS.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
67
68
69
70
71
72
73
74
75
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
long startTime = SystemClock.elapsedRealtime();
ProcessRecord app;
//isolated是false
if (!isolated) {
//根据进程名和uid去进程列表查找ProcessRecord
app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
//如果是后台进程且该进程在bad进程列表则返回
if (mAppErrors.isBadProcessLocked(info)) {
return null;
}
} else {
//如果是显式启动的进程,则清除进程的崩溃计数,并把它从bad进程列表中清除
mAppErrors.resetProcessCrashTimeLocked(info);
if (mAppErrors.isBadProcessLocked(info)) {
mAppErrors.clearBadProcessLocked(info);
if (app != null) {
app.bad = false;
}
}
}
} else {
app = null;
}
//如果存在该进程的ProcessRecord并且pid不为0,
if (app != null && app.pid > 0) {
//knownToBeDead为true
if ((!knownToBeDead && !app.killed) || app.thread == null) {
//如果ProcessRecord存在但未绑定客户端IApplicationThread本地代理,则添加新的包信息并返回
app.addPackage(info.packageName, info.versionCode, mProcessStats);
return app;
}
//如果该ProcessRecord已经被附加到前一个进程,则干掉并清理该进程组
killProcessGroup(app.uid, app.pid);
handleAppDiedLocked(app, true, true);
}

String hostingNameStr = hostingName != null ? hostingName.flattenToShortString() : null;
if (app == null) {
//构造新的ProcessRecord,其中isolated是false,app.isolated也是false
app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
if (app == null) {
return null;
}
app.crashHandler = crashHandler;
app.isolatedEntryPoint = entryPoint;
app.isolatedEntryPointArgs = entryPointArgs;
} else {
//如果ProcessRecord存在,并添加新的包信息
app.addPackage(info.packageName, info.versionCode, mProcessStats);
}

//如果系统还没有准备好,则推迟启动此过程,直到系统准备好为止。
if (!mProcessesReady && !isAllowedWhileBooting(info) && !allowWhileBooting) {
if (!mProcessesOnHold.contains(app)) {
mProcessesOnHold.add(app);
}
return app;
}
final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
return success ? app : null;
}

这个方法从3种情况处理新进程所对应的ProcessRecord:
从前后台进程和bad进程列表的角度;存在或不存在该进程的ProcessRecord的2种情况;系统未准备好的情况。

AMS.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
67
68
69
70
private final boolean startProcessLocked(ProcessRecord app,String hostingType, String hostingNameStr, String abiOverride) {
return startProcessLocked(app, hostingType, hostingNameStr,false /* disableHiddenApiChecks */, abiOverride);
}

private final boolean startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
if (app.pendingStart) {
return true;
}
long startTime = SystemClock.elapsedRealtime();
//重置ProcessRecord的pid
if (app.pid > 0 && app.pid != MY_PID) {
synchronized (mPidsSelfLocked) {
mPidsSelfLocked.remove(app.pid);
mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
}
app.setPid(0);
}
//如果ProcessRecord是被添加到待启动列表中然后启动的,则从待启动列表中移除。
mProcessesOnHold.remove(app);
updateCpuStats();
try {
try {
final int userId = UserHandle.getUserId(app.uid);
AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId);
} catch (RemoteException e) {
}
int uid = app.uid;
int[] gids = null;
int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
//app.isolated是false
if (!app.isolated) {
int[] permGids = null;
//通过PMS获取gids
try {
final IPackageManager pm = AppGlobals.getPackageManager();
permGids = pm.getPackageGids(app.info.packageName,
MATCH_DEBUG_TRIAGED_MISSING, app.userId);
StorageManagerInternal storageManagerInternal = LocalServices.getService(
StorageManagerInternal.class);
mountExternal = storageManagerInternal.getExternalStorageMountMode(uid,
app.info.packageName);
} catch (RemoteException e) {
}
if (ArrayUtils.isEmpty(permGids)) {
gids = new int[3];
} else {
gids = new int[permGids.length + 3];
System.arraycopy(permGids, 0, gids, 3, permGids.length);
}
gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
gids[1] = UserHandle.getCacheAppGid(UserHandle.getAppId(uid));
gids[2] = UserHandle.getUserGid(UserHandle.getUserId(uid));
if (gids[0] == UserHandle.ERR_GID) gids[0] = gids[2];
if (gids[1] == UserHandle.ERR_GID) gids[1] = gids[2];
}
...
app.gids = gids;
app.requiredAbi = requiredAbi;
app.instructionSet = instructionSet;
...
//设置新进程的入口点,后面会反射entryPoint并调用其main方法。
final String entryPoint = "android.app.ActivityThread";
//真正创建进程。创建成功则返回新进程PID
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids, runtimeFlags,
mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime);
} catch (RuntimeException e) {
...
}
}

设置创建进程需要的参数,最主要是设置新进程的入口函数android.app.ActivityThread

AMS.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
private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
app.pendingStart = true;
app.killedByAm = false;
app.removed = false;
app.killed = false;
final long startSeq = app.startSeq = ++mProcStartSeqCounter;
app.setStartParams(uid, hostingType, hostingNameStr, seInfo, startTime);
//这个标记代表是否异步启动新进程,FLAG_PROCESS_START_ASYNC默认值是true。
if (mConstants.FLAG_PROCESS_START_ASYNC) {
mProcStartHandler.post(() -> {
try {
synchronized (ActivityManagerService.this) {
final String reason = isProcStartValidLocked(app, startSeq);
if (reason != null) {
app.pendingStart = false;
return;
}
app.usingWrapper = invokeWith != null
|| SystemProperties.get("wrap." + app.processName) != null;
mPendingStarts.put(startSeq, app);
}
final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
requiredAbi, instructionSet, invokeWith, app.startTime);
synchronized (ActivityManagerService.this) {
handleProcessStartedLocked(app, startResult, startSeq);
}
} catch (RuntimeException e) {
synchronized (ActivityManagerService.this) {
mPendingStarts.remove(startSeq);
app.pendingStart = false;
forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
false, false, true, false, false,
UserHandle.getUserId(app.userId), "start failure");
}
}
});
return true;
} else {
try {
final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
invokeWith, startTime);
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
} catch (RuntimeException e) {
app.pendingStart = false;
forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
false, true, false, false,UserHandle.getUserId(app.userId), "start failure");
}
return app.pid > 0;
}
}

这里是异步启动进程,调用startProcess()

AMS.startProcess
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private ProcessStartResult startProcess(String hostingType, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
try {
final ProcessStartResult startResult;
if (hostingType.equals("webview_service")) {
startResult = startWebView(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null,
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,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
}
return startResult;
}
}
Process.start
1
2
3
4
5
6
7
public static final ProcessStartResult start(final String processClass, final String niceName,
int uid, int gid, int[] gids, int runtimeFlags, int mountExternal,
int targetSdkVersion, String seInfo, String abi, String instructionSet,
String appDataDir, String invokeWith, String[] zygoteArgs) {
return zygoteProcess.start(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal,
targetSdkVersion, seInfo, abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}
ZygoteProcess.start
1
2
3
4
5
6
7
8
9
10
11
12
13
public final Process.ProcessStartResult start(final String processClass, final String niceName,
int uid, int gid, int[] gids, int runtimeFlags,
int mountExternal, int targetSdkVersion, String seInfo,
String abi, String instructionSet, String appDataDir,
String invokeWith, String[] zygoteArgs) {
try {
return startViaZygote(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal,
targetSdkVersion, seInfo, abi, instructionSet, appDataDir, invokeWith,
false /* startChildZygote */, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
throw new RuntimeException("Starting VM process through Zygote failed", ex);
}
}

方法的注释说的比较清楚:启动新的进程,然后调用processClass这个类的main()函数。在Zygote进程fork子进程完毕后会用到这个参数。

ZygoteProcess.startViaZygote
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private Process.ProcessStartResult startViaZygote(final String processClass, final String niceName,
final int uid, final int gid, final int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion, String seInfo, String abi,
String instructionSet, String appDataDir,
String invokeWith, boolean startChildZygote,
String[] extraArgs) throws ZygoteStartFailedEx {
ArrayList<String> argsForZygote = new ArrayList<String>();
...
//processClass是"android.app.ActivityThread"
argsForZygote.add(processClass);
...
synchronized(mLock) {
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
}
}

这里分为3个步骤:
argsForZygote: 把启动需要的参数按照顺序放到ArrayList中,因为取出也是按照顺序的;
openZygoteSocketIfNeeded(): 创建LocalSocket并连接到Zygote进程的LocalServerSocket,然后根据cpu架构返回一个ZygoteState;
zygoteSendArgsAndGetResult(): 向Zygote进程发送argsForZygote

先看openZygoteSocketIfNeeded()

ZygoteProcess.openZygoteSocketIfNeeded
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
private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
try {
primaryZygoteState = ZygoteState.connect(mSocket);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
}
maybeSetApiBlacklistExemptions(primaryZygoteState, false);
maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
}
if (primaryZygoteState.matches(abi)) {
return primaryZygoteState;
}
if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
try {
secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
}
maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
}
if (secondaryZygoteState.matches(abi)) {
return secondaryZygoteState;
}
throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}

mSocket & mSecondarySocket:LocalSocketAddress;
primaryZygoteState & secondaryZygoteState:ZygoteState。封装了与Zygote进程进行Socket通信的LocalSocket和LocalSocket的输入输出流;

ZygoteState.connect
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static ZygoteState connect(LocalSocketAddress address) throws IOException {
DataInputStream zygoteInputStream = null;
BufferedWriter zygoteWriter = null;
final LocalSocket zygoteSocket = new LocalSocket();
try {
zygoteSocket.connect(address);
zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
zygoteWriter = new BufferedWriter(new OutputStreamWriter(
zygoteSocket.getOutputStream()), 256);
} catch (IOException ex) {
try {
zygoteSocket.close();
} catch (IOException ignore) {
}
throw ex;
}
String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
Arrays.asList(abiListString.split(",")));
}

构造LocalSocket,调用connect();获取用于Socket的输入流和输出流,封装到ZygoteState中。

LocalSocket.connect
1
2
3
4
5
6
7
8
9
10
11
public void connect(LocalSocketAddress endpoint) throws IOException {
synchronized (this) {
if (isConnected) {
throw new IOException("already connected");
}
implCreateIfNeeded();
impl.connect(endpoint, 0);
isConnected = true;
isBound = true;
}
}

impl:LocalSocketImpl,通过jni调用底层Socket代码。
LocalSocket和Zygote进程的LocalServerSocket均由LocalSocketImpl实现。

SystemServer进程和Zygote进行进行通信的LocalSocket创建并连接完成,然后zygoteSendArgsAndGetResult()是发送数据。

ZygoteProcess.zygoteSendArgsAndGetResult
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
private static Process.ProcessStartResult zygoteSendArgsAndGetResult(ZygoteState zygoteState, ArrayList<String> args)
throws ZygoteStartFailedEx {
try {
int sz = args.size();
for (int i = 0; i < sz; i++) {
if (args.get(i).indexOf('\n') >= 0) {
throw new ZygoteStartFailedEx("embedded newlines not allowed");
}
}
final BufferedWriter writer = zygoteState.writer;
final DataInputStream inputStream = zygoteState.inputStream;
writer.write(Integer.toString(args.size()));
writer.newLine();
for (int i = 0; i < sz; i++) {
String arg = args.get(i);
writer.write(arg);
writer.newLine();
}
writer.flush();

Process.ProcessStartResult result = new Process.ProcessStartResult();
result.pid = inputStream.readInt();
result.usingWrapper = inputStream.readBoolean();
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
return result;
} catch (IOException ex) {
zygoteState.close();
throw new ZygoteStartFailedEx(ex);
}
}

通过Socket的输入流输出流向Zygote进程发送创建进程的数据,然后返回进程的pid

再看Zygote进程如何接受Socket通信。

ZygoteInit.main
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
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
...
final Runnable caller;
try {
...
boolean startSystemServer = false;
String socketName = "zygote";
String abiList = null;
boolean enableLazyPreload = false;
for (int i = 1; i < argv.length; i++) {
if ("start-system-server".equals(argv[i])) {
startSystemServer = true;
} else if ("--enable-lazy-preload".equals(argv[i])) {
enableLazyPreload = true;
} else if (argv[i].startsWith(ABI_LIST_ARG)) {
abiList = argv[i].substring(ABI_LIST_ARG.length());
} else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
socketName = argv[i].substring(SOCKET_NAME_ARG.length());
} else {
throw new RuntimeException("Unknown command line argument: " + argv[i]);
}
}
if (abiList == null) {
throw new RuntimeException("No ABI list supplied.");
}
//构造LocalServerSocket
zygoteServer.registerServerSocketFromEnv(socketName);
...
//GC
gcAndFinalize();
...
if (startSystemServer) {//启动SystemServer进程执行
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
if (r != null) {
r.run();
return;
}
}
//开启循环监听
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
if (caller != null) {
caller.run();
}
}

首先调用zygoteServer.registerServerSocketFromEnv(socketName)构造LocalServerSocket.

ZygoteServer.registerServerSocketFromEnv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void registerServerSocketFromEnv(String socketName) {
if (mServerSocket == null) {
int fileDesc;
final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
try {
String env = System.getenv(fullSocketName);
fileDesc = Integer.parseInt(env);
} catch (RuntimeException ex) {
throw new RuntimeException(fullSocketName + " unset or invalid", ex);
}
try {
FileDescriptor fd = new FileDescriptor();
fd.setInt$(fileDesc);
mServerSocket = new LocalServerSocket(fd);
mCloseSocketFd = true;
} catch (IOException ex) {
throw new RuntimeException("Error binding to local socket '" + fileDesc + "'", ex);
}
}
}

mServerSocket:LocalServerSocket。

然后调用runSelectLoop(),开启监听SystemServer进程中AMS发送来的消息。

ZygoteServer.runSelectLoop
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
Runnable runSelectLoop(String abiList) {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
fds.add(mServerSocket.getFileDescriptor());
peers.add(null);
while (true) {
StructPollfd[] pollFds = new StructPollfd[fds.size()];
for (int i = 0; i < pollFds.length; ++i) {
pollFds[i] = new StructPollfd();
pollFds[i].fd = fds.get(i);
pollFds[i].events = (short) POLLIN;
}
try {
//轮询状态,监听LocalServerSocket的FileDescriptor,有事件则往下执行,否则阻塞在这里。
Os.poll(pollFds, -1);
} catch (ErrnoException ex) {
throw new RuntimeException("poll failed", ex);
}
for (int i = pollFds.length - 1; i >= 0; --i) {
if ((pollFds[i].revents & POLLIN) == 0) {
continue;
}
if (i == 0) {
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
} else {
try {
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
if (mIsForkChild) {
if (command == null) {
throw new IllegalStateException("command == null");
}
return command;
} else {
if (command != null) {
throw new IllegalStateException("command != null");
}
if (connection.isClosedByPeer()) {
connection.closeSocket();
peers.remove(i);
fds.remove(i);
}
}
} catch (Exception e) {
if (!mIsForkChild) {
ZygoteConnection conn = peers.remove(i);
conn.closeSocket();
fds.remove(i);
} else {
throw e;
}
} finally {
mIsForkChild = false;
}
}
}
}
}

当有客户端Socket连接到mServerSocket也就是LocalServerSocket时,先调用acceptCommandPeer()方法构造ZygoteConnection,然后使用processOneCommand()处理这个请求。
acceptCommandPeer():调用mServerSocket.accept()拿到连接的LocalSocket,然后把这个LocalSocket和它的输入流输出流放到ZygoteConnection中。
processOneCommand():调用Zygote.forkAndSpecializefork子进程。

ZygoteConnection.acceptCommandPeer
1
2
3
4
5
6
7
private ZygoteConnection acceptCommandPeer(String abiList) {
try {
return createNewConnection(mServerSocket.accept(), abiList);
} catch (IOException ex) {
throw new RuntimeException("IOException during accept()", ex);
}
}
ZygoteConnection.processOneCommand
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
Runnable processOneCommand(ZygoteServer zygoteServer) {
...
int pid = -1;
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.runtimeFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName, fdsToClose, fdsToIgnore, parsedArgs.startChildZygote,
parsedArgs.instructionSet, parsedArgs.appDataDir);
try {
//子进程
if (pid == 0) {
zygoteServer.setForkChild();
zygoteServer.closeServerSocket();
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
return handleChildProc(parsedArgs, descriptors, childPipeFd,
parsedArgs.startChildZygote);
} else {
//父进程
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
handleParentProc(pid, descriptors, serverPipeFd);
return null;
}
}
}

有关Linux的fork子进程的相关原理:如子进程fork成功,子进程会完全的和父进程相同,包括当前代码执行的状态。
我的理解是:

  • 复制子进程之前只有一个Zygote进程,系统先暂停Zygote进程并保存当前Zygote进程快照;
  • 开始创建子进程并完全拷贝Zygote进程快照;
  • 子进程fork完毕后,当前除了Zygote进程还有一个与Zygote进程代码资源和运行状态完全一致的子进程,此时这个两个进程已经是彼此独立分离的;
  • Zygote进程和子进程均被唤醒,Zygote进程继续往下执行返回pid,而子进程于Zygote进程完全一致,也被唤醒然后返回pid,它俩完全在两条独立的分支上运行了;
  • Zygote进程继续监听客户端Socket的连接,而fork出来的子进程最终反射调用ActivityThreadmain方法。

此时代码的运行状态是:子进程返回的pid等于0,执行handleChildProc();Zygote进程返回的pid大于0,继续监听客户端Socket的消息。

ZygoteConnection.handleChildProc
1
2
3
4
5
6
7
8
9
10
11
12
13
private Runnable handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors,
FileDescriptor pipeFd, boolean isZygote) {
//关闭LocalSocket连接
closeSocket();
。。。
if (!isZygote) {
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs,
null /* classLoader */);
} else {
return ZygoteInit.childZygoteInit(parsedArgs.targetSdkVersion,
parsedArgs.remainingArgs, null /* classLoader */);
}
}
ZygoteInit.childZygoteInit
1
2
3
4
static final Runnable childZygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
RuntimeInit.Arguments args = new RuntimeInit.Arguments(argv);
return RuntimeInit.findStaticMain(args.startClass, args.startArgs, classLoader);
}
RuntimeInit.findStaticMain
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
protected static Runnable findStaticMain(String className, String[] argv,ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
}
...
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
}
...
return new MethodAndArgsCaller(m, argv);
}

static class MethodAndArgsCaller implements Runnable {

private final Method mMethod;
private final String[] mArgs;

public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
}
...
}
}

findStaticMain()返回MethodAndArgsCaller对象,这个Runnable的run方法便是反射调用'android.app.ActivityThread'main方法,这便是通常被认为的应用程序的入口。

总结:
Zygote进程孵化了SystemServer进程和相应系统服务;
SystemServer进程使用Socket向Zygote进程通信,完成新进程的创建,创建是通过fork了Zygote进程完成的;
新fork出来的进程入口处在'android.app.ActivityThread'main方法。

新进程入口ActivityThread.main()
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
...
//绑定主线程到Loop。
Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);

//开启Loop消息循环。
Looper.loop();
//不会执行到这里,除非主线程意外结束。
throw new RuntimeException("Main thread loop unexpectedly exited");
}

开启了主线程消息循环;
初始化ActivityThread,在ActivityThread中初始化了几个重要的变量:
final ApplicationThread mAppThread = new ApplicationThread(): 代表新进程的Binder,用于和AMS进程相护进行Binder通信,前面有解释。
final H mH = new H():主线程Handler,处理4大组件生命周期。
调用attach()方法完成后续的工作。

ActivityThread.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
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;//app进程是false
if (!system) {
ViewRootImpl.addFirstDrawHandler(new Runnable() {
@Override
public void run() {
//开启JIT即时编译,假如VM虚拟机支持。
ensureJitEnabled();
}
});
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
//添加GC观察者,内存超4分之3时,通知AMS释放当前客户端进程指定状态的Activity。
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)) {
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
}
...
}

初始化一些状态,然后调用mgr.attachApplication(),把代表当前客户端进程的ApplicationThread绑定到AMS,这是因为客户端进程有关四大组件的权限控制还是要交给AMS来管理。
mgr:通过ActivityManager.getService()所获得的AMS在客户端进程的本地代理,这个本地代理具有跨进程调用AMS进程相关方法的能力。

经过Binder驱动,AMS.attachApplication()被调用。

AMS.attachApplication
1
2
3
4
5
6
7
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
}
}

thread:客户端ApplicationThread在AMS进程的本地代理,它具有与thread所在进程进行IPC的能力。

AMS.attachApplicationLocked
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
//首先检查pid列表中是否有对应的ProcessRecord
ProcessRecord app;
long startTime = SystemClock.uptimeMillis();
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid);
}
} else {
app = null;
}
//如果pid列表没有ProcessRecord则去mPendingStarts列表查询,并添加到pid列表中。
if (app == null && startSeq > 0) {
final ProcessRecord pending = mPendingStarts.get(startSeq);
if (pending != null && pending.startUid == callingUid
&& handleProcessStartedLocked(pending, pid, pending.usingWrapper,
startSeq, true)) {
app = pending;
}
}
//如果此时还没有ProcessRecord,则代表杀掉该pid的进程并返回。
if (app == null) {
if (pid > 0 && pid != MY_PID) {
killProcessQuiet(pid);
} else {
try {
thread.scheduleExit();
} catch (Exception e) {
}
}
return false;
}
//如果该ProcessRecord还附加在上一个进程,则清理ProcessRecord。
if (app.thread != null) {
handleAppDiedLocked(app, true, true);
}
//为thread这个Binder添加一个承载Binder到进程消失时用来接收回调的接口
final String processName = app.processName;
try {
AppDeathRecipient adr = new AppDeathRecipient(app, pid, thread);
thread.asBinder().linkToDeath(adr, 0);
app.deathRecipient = adr;
} catch (RemoteException e) {
app.resetPackageList(mProcessStats);
//重新创建进程
startProcessLocked(app, "link fail", processName);
return false;
}
//重置ProcessRecord的app.thread等一系列参数。
app.makeActive(thread, mProcessStats);
app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;
app.curSchedGroup = app.setSchedGroup = ProcessList.SCHED_GROUP_DEFAULT;
app.forcingToImportant = null;
updateProcessForegroundLocked(app, false, false);
app.hasShownUi = false;
app.debugging = false;
app.cached = false;
app.killedByAm = false;
app.killed = false;
app.unlocked = StorageManager.isUserKeyUnlocked(app.userId);
//移除创建进程超时的message
mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
//如果系统准备好或该进程是持久进程,通常就是true
boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);

List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
//如果该进程存在需要启动的ContentProvider,则发送一个延时10s的ANR消息
if (providers != null && checkAppInLaunchingProvidersLocked(app)) {
Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG);
msg.obj = app;
mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT);
}
try {
...
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
} catch (Exception e) {
//如果bind失败,尝试重新启动进程,但这很容易无限循环的重新启动进程。
app.resetPackageList(mProcessStats);
app.unlinkDeathRecipient();
startProcessLocked(app, "bind fail", processName);
return false;
}
//是否出现异常等问题
boolean badApp = false;
//表示是否有启动四大组件
boolean didSomething = false;

//检查当前进程中栈顶可见的Activity是否在等待运行
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
badApp = true;
}
}

//检查当前进程中是否有应该运行的Service。
if (!badApp) {
try {
didSomething |= mServices.attachApplicationLocked(app, processName);
} catch (Exception e) {
badApp = true;
}
}

//检查下一个BroadcastReceiver是否在当前进程中。
if (!badApp && isPendingBroadcastProcessLocked(pid)) {
try {
didSomething |= sendPendingBroadcastsLocked(app);
} catch (Exception e) {
badApp = true;
}
}

//检查当前进程中是否有备份代理。
if (!badApp && mBackupTarget != null && mBackupTarget.app == app) {
notifyPackageUse(mBackupTarget.appInfo.packageName,
PackageManager.NOTIFY_PACKAGE_USE_BACKUP);
try {
thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
mBackupTarget.backupMode);
} catch (Exception e) {
badApp = true;
}
}
//如果发生了错误,杀掉app进程
if (badApp) {
app.kill("error during init", true);
handleAppDiedLocked(app, false, true);
return false;
}
if (!didSomething) {
updateOomAdjLocked();
}
return true;
}

检查thread所在进程相对应AMS中保存的ProcessRecord信息是否有异常;
重置ProcessRecord的状态并绑定客户端进程的IApplicationThread本地代理;
移除创建进程超时的message;
如果该进程存在需要启动的ContentProvider,则发送一个延时10s的ANR消息;
创建客户端进程的Application;
处理Activity、Service和BroadcastReceiver系统组件。

AMS通知App创建Application

AMS调用thread.bindApplication(),经过Binder驱动,最终客户端进程的ApplicationThread.bindApplication()被调用;

ApplicationThread.bindApplication
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
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, boolean autofillCompatibilityEnabled) {
if (services != null) {
//把常用的系统服务缓存在ServiceManager中。
ServiceManager.initServiceCache(services);
}
setCoreSettings(coreSettings);

AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillCompatibilityEnabled = autofillCompatibilityEnabled;
sendMessage(H.BIND_APPLICATION, data);
}

sendMessage(H.BIND_APPLICATION, data)发送BIND_APPLICATION消息到mH,然后在主线程中调用ActivityThread.handleBindApplication()

ActivityThread.handleBindApplication
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
private void handleBindApplication(AppBindData data) {
...

//为data.info创建LoadedApk,
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
...
//ii是InstrumentationInfo,一般为空,创建Instrumentation
if (ii != null) {
...
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
...
Application app;
try {
//创建Application,由LoadedApk完成
app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
...
//回调Application的onCreate()方法
try {
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
}
}
...
}

调用getPackageInfoNoCheck()创建LoadedApk,LoadedApk是内存形式的.apk文件;
创建Instrumentation;
使用LoadedApk创建Application;
调用Instrumentation回调Application的onCreate()方法。

LoadedApk.makeApplication
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
public Application makeApplication(boolean forceDefaultAppClass,Instrumentation instrumentation) {
//创建过Application则直接返回
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
//反射构造Application
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
}
mActivityThread.mAllApplications.add(app);
//缓存Application
mApplication = app;

...
return app;
}

检查是否创建过Application;得到Application类名、ContextImp和ClassLoader,然后借助Instrumentation去构造Application;最后把Application缓存起来;
接着看Instrumentation.newApplication()

1
2
3
4
5
6
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Application app = getFactory(context.getPackageName()).instantiateApplication(cl, className);
app.attach(context);
return app;
}

getFactory():AppComponentFactory,它是用于管理manifest文件中的Application和4大组件实例化的接口。
AppComponentFactory.instantiateApplication()

1
2
3
4
public @NonNull Application instantiateApplication(ClassLoader cl, String className)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Application) cl.loadClass(className).newInstance();
}

最终Application通过反射的方式生成了,然后attach()被调用,当使用LoadedApk创建Application完毕后,回到ActivityThread.handleBindApplication,紧接着调用Instrumentation.callApplicationOnCreate()回调Application的onCreate()方法。

Instrumentation.callApplicationOnCreate
1
2
3
public void callApplicationOnCreate(Application app) {
app.onCreate();
}

很简洁!
AMS进程和客户端进程进行IPC;
客户端进程创建LoadedApk和Instrumentation;
使用LoadedApk创建Application;
调用Instrumentation回调Application的onCreate()方法。

AMS通知App创建Activity并回调相关生命周期

回到AMS.attachApplicationLocked(),AMS通知客户端进程创建完Application之后,调用mStackSupervisor.attachApplicationLocked()处理Activity:

ActivityStackSupervisor.attachApplicationLocked
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
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getChildAt(stackNdx);
if (!isFocusedStack(stack)) {
continue;
}
stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
for (int i = 0; i < size; i++) {
final ActivityRecord activity = mTmpActivityList.get(i);
if (activity.app == null && app.uid == activity.info.applicationInfo.uid
&& processName.equals(activity.processName)) {
try {
//真正启动Activity的方法
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {
didSomething = true;
}
} catch (RemoteException e) {
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}

从后向前遍历当前显示屏幕上的Activity栈,如果这个栈没有焦点则跳出循环;
遍历这个栈中所有的ActivityRecord,判断ActivityRecord是否绑定了ProcessRecord、uid是否相同、进程名是否相同;
如果这3个条件都满足,则取出这个栈的栈顶处于运行状态的ActivityRecord,调用realStartActivityLocked()方法启动Activity。
app:客户端进程中对应的ProcessRecord;
activity:客户端进程中待启动Activity对应的ActivityRecord。
andResume:true,启动后进行resume操作。

ActivityStackSupervisor.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
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
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//有Activity的onPause未结束,不往下进行
if (!allPausedActivitiesComplete()) {
return false;
}

final TaskRecord task = r.getTask();
final ActivityStack stack = task.getStack();

try {
//设置ActivityRecord和ProcessRecord的一些参数等
r.startFreezingScreenLocked(app, 0);
r.startLaunchTickingLocked();
r.setProcess(app);
...
app.waitingToKill = null;
r.launchCount++;
r.lastLaunchTime = SystemClock.uptimeMillis();

int idx = app.activities.indexOf(r);
if (idx < 0) {
app.activities.add(r);
}
//更新进程列表,更新进程oom adj值
mService.updateLruProcessLocked(app, true, null);
mService.updateOomAdjLocked();

try {
if (app.thread == null) {
throw new RemoteException();
}
List<ResultInfo> results = null;
List<ReferrerIntent> newIntents = null;
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
if (r.isActivityTypeHome()) {
mService.mHomeProcess = task.mActivities.get(0).app;
}
mService.notifyPackageUse(r.intent.getComponent().getPackageName(),
PackageManager.NOTIFY_PACKAGE_USE_ACTIVITY);
r.sleeping = false;
r.forceNewConfig = false;
mService.getAppWarningsLocked().onStartActivity(r);
mService.showAskCompatModeDialogLocked(r);
r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);

app.hasShownUi = true;
app.pendingUiClean = true;
app.forceProcessStateUpTo(mService.mTopProcessState);

//创建启动Activity并进行Resume的事务。
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
final ActivityLifecycleItem lifecycleItem;
//andResume为true,后续执行Resume流程。
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);

} catch (RemoteException e) {
if (r.launchFailed) {
//如果是第二次失败,则关闭Activity
mService.appDiedLocked(app);
stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
"2nd-crash", false);
return false;
}
// 第一次失败添加一个标记
r.launchFailed = true;
app.activities.remove(r);
throw e;
}
}
r.launchFailed = false;
if (andResume && readyToResume()) {
//更新Resume状态等
stack.minimalResumeActivityLocked(r);
} else {
r.setState(PAUSED, "realStartActivityLocked");
}
...
//更新与Activity进行bind的Service的IServiceConnection
if (r.app != null) {
mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
}
return true;
}

Activity的启动和运行,AMS通过事务的统一发送到客户端进程。这个过程类似于AMS发送事务让Launcher进入后台执行pause操作,经过Binder驱动,最终来到客户端进程,由客户端进程中ActivityThread的TransactionExecutor来处理AMS发送的ClientTransaction
TransactionExecutor先后处理ClientTransactionmActivityCallbacksmLifecycleStateRequest,其中mActivityCallbacks便是LaunchActivityItem,作用是创建Activity并回调onCreate()方法;
先看LaunchActivityItem:

LaunchActivityItem.execute
1
2
3
4
5
6
7
8
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);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}

client:ActivityThread父类,定义了抽象方法由ActivityThread实现;
token:AMS进程中,是代表Activity的ActivityRecord所保存的Token(Binder)在客户端进程的本地代理,
构造ActivityClientRecord,调用ActivityThread.handleLaunchActivity()

ActivityThread.handleLaunchActivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public Activity handleLaunchActivity(ActivityClientRecord r ,
PendingTransactionActions pendingActions, Intent customIntent) {
...
//初始化WMS
WindowManagerGlobal.initialize();
//创建Activity
final Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
...
} else {
//出现异常,通知AMS停止自己
try {
ActivityManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
return a;
}
ActivityThread.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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);
}
//创建Activity持有的BaseContext
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//由Instrumentation完成Activity的构造
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
}

try {
//创建Application,如果已创建则直接返回
Application app = r.packageInfo.makeApplication(false, mInstrumentation);

if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
appContext.setOuterContext(activity);
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);

if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}

activity.mCalled = false;
//回调Activity的onCreate方法
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;
}
r.setState(ON_CREATE);
//缓存token
mActivities.put(r.token, r);
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
}
return activity;
}

Instrumentation.newActivity():类似Application的创建,最终调用AppComponentFactory.instantiateActivity()反射构造Activity;
activity.attach():Activity自己的初始化;
mInstrumentation.callActivityOnCreate():先调用activity.performCreate(),再回调Activity.onCreate()

分析完了LaunchActivityItem如何创建Activity并回调onCreate()方法后,再看TransactionExecutor如何处理ClientTransaction的mLifecycleStateRequest
通过前面的文章分析知道,TransactionExecutor再处理ClientTransaction时,会通过cycleToPath()以及performLifecycleSequence()方法,处理当前声明周期状态到目标声明周期中间的声明周期,在LaunchActivityItem处理完毕后,当前状态是ON_CREATE,而目标状态是ON_RESUME,所以cycleToPath()会在处理ResumeActivityItem前先调用ActivityThread.handleStartActivity()完成Activity的onStart()方法的回调。处理完cycleToPath()以后,TransactionExecutor再处理ResumeActivityItem,ResumeActivityItem最终回调Activity的onResume()方法,具体的流程不在分析。
(点击查看)
这个时候Activity便显示出来了。

总结
  • 分析Activity启动过程更多的是分析SystemServer进程的AMS和客户端进程之间的通信。包括Launcher进程、AMS进程、待启动App进程。
  • 有2个重要的Binder贯穿了这个通信过程。首先是AMS为Activity创建的ActivityRecord的内部类Token,它被保存在ActivityRecord中,ActivityRecord被保存在AMS中,当Token传递到客户端进程中时,又被客户端进程的ActivityThread保存起来;然后是客户端进程被fork出来后,ActivityThread的内部类ApplicationThread,它代表着当前进程用来和其他系统进程进行通信,ApplicationThread的本地代理随后被保存到AMS中。这样AMS通过ApplicationThread的本地代理控制着客户端进程,而客户端处理问题则带着保存的Token本地代理再传给AMS,让AMS查找到对应的ActivityRecord。
  • AMS进程通过Socket和Zygote进程通信,进行fork子进程的操作,子进程fork成功后,回调用ActivithThread.main()
  • 有关Activity的启动模式和FLAG均由AMS处理,在ActivityStarter.startActivityUnchecked()中。
  • 下一个Activity的显示必须等到上一个Activity执行完onPause()。
  • 如果待启动Activity的进程已经存在,则在ActivityStackSupervisor.startSpecificActivityLocked()时,直接调用ActivityStackSupervisor.realStartActivityLocked(),省略创建进程的步骤了。
  • 是Zygote进程创建了SystemServer进程,见ZygoteInit.main()中执行的forkSystemServer()方法。
  • 以后再补充。。。

最后来一张完整图片来概括整个过程:
(点击查看大图)