Activity启动流程

前言

Activity的启动分为两种

  1. Activity中通过startActivity()方法启动一个Activity
  2. 从桌面通过点击应用图标启动一个APP然后显示Activity

image-20241020164604058

重点关注以下几个类的源码:

  1. ActivityStarter
  2. ActivityStackSupervisor
  3. ActivityStack
  4. ActivityManagerService
  5. ActivityThread

重点关注以下方法:

  • ActivityStarter.execute()
  • ActivityStackSupervisor.realStartActivityLocked()
  • ActivityStack.resumeTopActivityUncheckedLocked()
  • ActivityThread.handleLaunchActivity()

一、Launcher向AMS发送启动Activity

  1. Launcher进程通过点击图标生成Intent,然后调用startActivity()方法

  2. startActivity()最终会调用到Instrumentation的execStartActivity()方法

  3. 在execStartActivity()中,会通过Binder IPC调用ATMS(ActivityTaskManagerService)的startActivity()方法

  4. 具体的Binder调用过程是:获取IActivityTaskManager的单例对象

    • 获取IActivityTaskManager的单例对象
1
IActivityTaskManager.Stub.asInterface(ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE))
  • 通过该Binder代理对象调用ATMS的startActivity()方法

Launcher

Launcher本身是一个Activity,在用户点击应用图标时,调用startActivitySafely方法,最后调用到Activity.startActivity(),函数调用如下

1
2
3
4
5
6
7
8
9
// Launcher.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
...
//标记在新的栈启动
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
startActivity(intent, optsBundle);
...
}

Activity

继续在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
45
46
47
48
49
50
51
52
53
54
55
56
// Activity.java
@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 {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
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) {
...
// 注重点 1️⃣
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
...
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}

public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
int requestCode) {
startActivityFromChild(child, intent, requestCode, null);
}
public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
int requestCode, @Nullable Bundle options) {
options = transferSpringboardActivityOptions(options);
// 注重点 2️⃣
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, child,
intent, requestCode, options);
...
}

Instrumentation

Instrumentation.execStartActivity()函数中传入了mMainThread.getApplicationThread(),它获取到的是ActivityThread的内部类ApplicationThread,这是一个Binder对象,之后AMS通过此对象与App的通信。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Instrumentation.java
@UnsupportedAppUsage
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
...
// 重点1️⃣
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
...
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}

ActivityTaskManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// ActivityTaskManager.java
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}

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

这是一个使用Singleton模式的私有静态常量,用于确保IActivityTaskManager只有一个实例。

  1. Singleton模式: 使用Singleton确保IActivityTaskManager服务只有一个实例,这有助于节省系统资源并保证一致性。
  2. 延迟初始化: 服务实例不是在类加载时就创建的,而是在首次调用get()方法时才会创建,这是延迟初始化的一个例子。
  3. ServiceManager: 使用ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE)获取系统级的ACTIVITY_TASK_SERVICE服务。
  4. AIDL: IActivityTaskManager.Stub.asInterface(b)是典型的AIDL(Android接口定义语言)用法,用于跨进程通信。它将IBinder对象转换为IActivityTaskManager接口。
工作流程
  1. 当调用ActivityTaskManager.getService()时,它会返回IActivityTaskManagerSingleton的实例。
  2. 如果是首次调用,Singleton会调用create()方法:通过ServiceManager获取ACTIVITY_TASK_SERVICE的IBinder对象。将IBinder对象转换为IActivityTaskManager接口。
  3. 后续调用会直接返回已创建的实例,无需重新创建。

二、AMS启动Activity并通知Launcher进入Paused状态

ActivityTaskManagerService

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
// ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
@Override
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());
}

、、、

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("startActivityAsUser");

userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

// TODO: Switch to user app stacks here.
// 重点1️⃣
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();

}

ActivityStartController

1
2
3
4
5
6
7
8
public class ActivityStartController {
...
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
...
}

ActivityStarter

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
class ActivityStarter {
/**
* Starts an activity based on the request parameters provided earlier.
* @return The starter result.
*/
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
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,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
} else {
// 调用startActivity 1️⃣
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
}
} finally {
onExecutionComplete();
}
}

private int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
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,
PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
final ActivityRecord[] outRecord = new ActivityRecord[1];
// 调用startActivity 2️⃣
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, originatingPendingIntent,
allowBackgroundActivityStart);
...
}
// 1️⃣ 和 2️⃣调用startActivity
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,
PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
// 调用startActivity 3️⃣
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, originatingPendingIntent,
allowBackgroundActivityStart);
...
}

// 4️⃣调用startActivity
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
....
// 调用startActivityUnchecked5️⃣
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
....


// 5️⃣调用startActivityUnchecked
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor, restrictedBgActivity);
...
final int preferredWindowingMode = mLaunchParams.mWindowingMode;
computeLaunchingTaskFlags(); // 6️⃣
computeSourceStack(); // 7️⃣
mIntent.setFlags(mLaunchFlags);
ActivityRecord reusedActivity = getReusableIntentActivity();
...
mRootActivityContainer.resumeFocusedStacksTopActivities(); // 8️⃣
...

}
  1. execute() 方法:
    这是ActivityStarter的入口方法。它根据mRequest.mayWait决定调用startActivityMayWait()还是startActivity()。通常情况下,我们关注不需要等待的情况,即调用startActivity()。
  2. startActivity() 方法 (1️⃣和2️⃣):
    这里有两个重载的startActivity方法。它们处理不同的参数,但最终都会调用到第三个startActivity方法。
  3. startActivity() 方法 (3️⃣):
    这个方法进一步处理启动Activity的请求,并调用下一个startActivity方法。
  4. startActivity() 方法 (4️⃣):
    这个方法创建ActivityRecord对象(如果还没有的话),并调用startActivityUnchecked()。
  5. startActivityUnchecked() 方法 (5️⃣):
    这是实际启动Activity的核心方法。它执行以下关键步骤:setInitialState(): 设置初始状态computeLaunchingTaskFlags() (6️⃣): 计算启动任务的标志computeSourceStack() (7️⃣): 计算源栈getReusableIntentActivity(): 尝试复用已存在的ActivitymRootActivityContainer.resumeFocusedStacksTopActivities() (8️⃣): 恢复焦点栈的顶部Activity
  6. computeLaunchingTaskFlags() (6️⃣):
    这个方法计算启动任务的标志,决定新Activity如何与现有任务交互。
  7. computeSourceStack() (7️⃣):
    计算源栈,确定新Activity应该放在哪个任务栈中。
  8. resumeFocusedStacksTopActivities() (8️⃣):
    这个方法负责恢复焦点栈的顶部Activity,实际上是将新启动的Activity带到前台。

RootActivityContainer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class RootActivityContainer extends ConfigurationContainer
implements DisplayManager.DisplayListener {
...
if (targetStack != null && (targetStack.isTopStackOnDisplay()
|| getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); // 标注1️⃣
}
...
if (!resumedOnDisplay) {
// In cases when there are no valid activities (e.g. device just booted or launcher
// crashed) it's possible that nothing was resumed on a display. Requesting resume
// of top activity in focused stack explicitly will make sure that at least home
// activity is started and resumed, and no recursion occurs.
final ActivityStack focusedStack = display.getFocusedStack();
if (focusedStack != null) {
focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions); // 标注2️⃣
}
}
...

return result;
}
}

ActivityStack

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
class ActivityStack extends ConfigurationContainer {

@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
...
result = resumeTopActivityInnerLocked(prev, options);
...
}

@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev,
ActivityOptions options) {
...
if (anim) {
next.applyOptionsLocked();
} else {
next.clearOptionsLocked();
}

mStackSupervisor.mNoAnimActivities.clear();

if (next.attachedToProcess()) { // 待启动的进程是否创建完成,如果没有就会到 else 中
...
} else {
// 标注1️⃣
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
...
}

}

ActivityStackSupervisor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
...
try {
...
// Post message to start process to avoid possible deadlock of calling into AMS with the
// ATMS lock held.
final Message msg = PooledLambda.obtainMessage(
// 标注1️⃣
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);
} finally {
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
}

标注1️⃣调用的其实是 ActivityManagerService内部类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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
@VisibleForTesting
public final class LocalService extends ActivityManagerInternal {
@Override
public void startProcess(String processName, ApplicationInfo info,
boolean knownToBeDead, 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) {
// 标注1️⃣
startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
new HostingRecord(hostingType, hostingName),
false /* allowWhileBooting */, false /* isolated */,
true /* keepIfLarge */);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}

// 标注1️⃣ 调用的方法
@GuardedBy("this")
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
HostingRecord hostingRecord, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
// 标注2️⃣
return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);
}
}
}

标注1️⃣调用:LocalService.startProcessLocked 方法。
在 LocalService.startProcessLocked 方法中又把进程创建的工作委派给了 ProcessList。
标注2️⃣调用:ProcessList的startProcessLocked方法

ProcessList

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
public final class ProcessList {
@GuardedBy("mService")
final void startProcessLocked(ProcessRecord app, HostingRecord hostingRecord) {
startProcessLocked(app, hostingRecord, null /* abiOverride */);
}
// 标注1️⃣ 调用的方法
@GuardedBy("mService")
final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
String abiOverride) {
// 标注2️⃣
return startProcessLocked(app, hostingRecord,
false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
}
@GuardedBy("mService")
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
if (!isolated) {
app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
}
...
// 标注1️⃣
final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
...
return success ? app : null;
}

/**
* @return {@code true} if process start is successful, false otherwise.
* @param app
* @param hostingRecord
* @param disableHiddenApiChecks
* @param abiOverride
*/
// 标注2️⃣ 调用的方法
@GuardedBy("mService")
boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
boolean disableHiddenApiChecks, boolean mountExtStorageFull,
String abiOverride) {
...
// 重点4️⃣:entryPoint 是新进程的入口。所以,Android 应用的程序入口是 ActivityThread。
final String entryPoint = "android.app.ActivityThread";
// 标注3️⃣
return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
...


// 标注3️⃣ 调用的方法
@GuardedBy("mService")
boolean startProcessLocked(HostingRecord hostingRecord,
String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {

...
// 标注5️⃣
final Process.ProcessStartResult startResult = startProcess(hostingRecord,
entryPoint, app,
uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
invokeWith, startTime);
// 标注6️⃣
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
...

// 标注6️⃣ 调用的方法
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
...
// 标注7️⃣
final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
// 标注8️⃣ 启动新的进程,入口是:ActivityThread.main()
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,
/*useUsapPool=*/ false,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
...
}
// 标注7️⃣ 调用的方法
private AppZygote createAppZygoteForProcessIfNeeded(final ProcessRecord app) {
synchronized (mService) {
...
AppZygote appZygote = mAppZygotes.get(app.info.processName, uid);
final ArrayList<ProcessRecord> zygoteProcessList;
if (appZygote == null) {
...
// 标注9️⃣ 创建AppZygote
appZygote = new AppZygote(appInfo, uid, firstUid, lastUid);
mAppZygotes.put(app.info.processName, uid, appZygote);
zygoteProcessList = new ArrayList<ProcessRecord>();
mAppZygoteProcesses.put(appZygote, zygoteProcessList);
} else {
...
mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG, appZygote);
zygoteProcessList = mAppZygoteProcesses.get(appZygote);
}
...
zygoteProcessList.add(app);

return appZygote;
}
}

}

标注9️⃣ : 创建AppZygote
标注8️⃣: 启动新的进程,入口是:ActivityThread.main(), 其中appZygote.getProcess()获取的是ChildZygoteProcess这个对象,ChildZygoteProcess又是ZygoteProcess的子类,也即是最终会调用ZygoteProcess.start方法

ZygoteProcess

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
public class ZygoteProcess {
public final Process.ProcessStartResult start(@NonNull final String processClass,
final String niceName,
int uid, int gid, @Nullable int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
@Nullable String seInfo,
@NonNull String abi,
@Nullable String instructionSet,
@Nullable String appDataDir,
@Nullable String invokeWith,
@Nullable String packageName,
boolean useUsapPool,
@Nullable String[] zygoteArgs) {
...

try {
// 标注1️⃣
return startViaZygote(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
packageName, useUsapPool, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
throw new RuntimeException(
"Starting VM process through Zygote failed", ex);
}
}
// 标注1️⃣调用的方法
private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
@Nullable final String niceName,
final int uid, final int gid,
@Nullable final int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
@Nullable String seInfo,
@NonNull String abi,
@Nullable String instructionSet,
@Nullable String appDataDir,
@Nullable String invokeWith,
boolean startChildZygote,
@Nullable String packageName,
boolean useUsapPool,
@Nullable String[] extraArgs)
throws ZygoteStartFailedEx {
synchronized(mLock) {
// The USAP pool can not be used if the application will not use the systems graphics
// driver. If that driver is requested use the Zygote application start path.
// 标注3️⃣ 使用socket调用
return
zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
useUsapPool,
argsForZygote);
}
}
}

此时还处于 system_server进程,这个类的目的是创建本地的 Socket 连接对象,连接到 Zygote 进程的 Socket 方法,然后通过字符输入流,把创建进程所需要的参数发送过去。

三、Zygote 进程接收请求并创建 Launcher 进程

有空再说

插曲

ATMS(ActivityTaskManagerService)和AMS(ActivityManagerService)之间的关系:

  1. 历史背景:在Android 10之前,AMS负责管理所有四大组件(Activity、Service、BroadcastReceiver和ContentProvider)以及进程生命周期。

  2. 职责分离:从Android 10开始,Google将Activity和Task相关的管理职责从AMS中分离出来,创建了ATMS。这样做的目的是为了优化系统性能和代码结构。

  3. 当前职责:ATMS: 主要负责Activity和Task的管理,包括Activity栈管理、生命周期控制等。AMS: 仍然负责管理Service、BroadcastReceiver、ContentProvider以及进程生命周期。

  4. 协作关系:ATMS和AMS紧密协作。例如,当需要启动一个新的Activity时,ATMS会处理Activity相关的逻辑,但可能需要AMS来处理进程创建等相关操作。

  5. 系统服务:两者都是系统级的服务,运行在system_server进程中。

  6. 接口变化:对于应用开发者来说,这种变化大多是透明的。但在系统层面,一些原本通过AMS进行的Activity相关操作现在需要通过ATMS来完成。

  7. 代码位置:ATMS: 位于frameworks/base/services/core/java/com/android/server/wm/目录下

    ​ AMS: 仍位于frameworks/base/services/core/java/com/android/server/am/目录下

  8. 未来趋势:这种分离是为了更好地支持多窗口和折叠屏等新特性,也为未来可能的架构优化铺平了道路。

Activity启动流程概括

  1. 点击桌面App图标,Launcher进程采用Binder IPC向system_server(AMS)进程发起startActivity请求;
  2. system_server(AMS)进程接收到请求后,交付 ActivityStarter 处理 Intent 和 Flag 等信息,然后再交给 ActivityStackSupervisior/ActivityStack 处理 Activity 进栈相关流程。同时以 Socket 方式请求 Zygote 进程 fork 新进程。
  3. Zygote 接收到新进程创建请求后 fork 出新进程。
  4. App进程,通过Binder IPC向sytem_server(AMS)进程发起attachApplication请求;
  5. system_server(AMS)进程在收到请求后,进行一系列准备工作后,调用ActivityStackSupervisior的realStartActivityLocked,接着通过binder IPC向App进程调用ApplicationThread的scheduleTransaction方法;
  6. App进程的binder线程(ApplicationThread)在收到请求后,调用ActivityThread的scheduleTransaction()方法,接着通过handler向主线程发送ActivityThread.H.EXECUTE_TRANSACTION消息;
  7. 主线程在收到Message后,ActivityThread经过一些内部逻辑处理,最终调用handleLaunchActivity()、handleResumeActivity()方法,这俩方法又分别调用performLaunchActivity()、performResumeActivity()方法。

performLaunchActivity()方法里面逻辑顺序:

  1. 创建ContextImpl 的实例appContext
  2. 利用 ClassLoader 去加载 Activity并创建 Activity 实例。
  3. 调用Activity 的attach方法,并把appContext 传进attach与Activity绑定,
    扩展:Activity 的attach方法里面会创建PhoneWindow实例,获取WindowManage实例,实际上是WindowManagerImpl(在SystemServiceRegistry里registerService中可以看到Context.WINDOW_SERVICE对应的是WindowManagerImpl)
  4. 创建Application实例,并在LoadedApk类中调用Instrumentation 的callApplicationOnCreate去调用Application的onCreate()方法

接着调用Instrumentation 的callActivityOnCreate()方法调用Activity的onCreate()方法
handleResumeActivity()方法里面逻辑顺序:

  1. 首先会执行performResumeActivity去调用Activity的onStart()、onResume(),返回ActivityClientRecord实例,通过此实例获取Activity
  2. 从Activity中获取PhoneWindow,
  3. 然后从PhoneWindow中获取到DecorView
  4. 接着从Activity中获取WindowManager(实际上是WindowManagerImpl)
  5. 再继续WindowManagerImpl调用addView()方法把DecorView添加进去
  6. WindowManagerImpld的addView()方法会调用到WindowManagerGlobal的addView()方法,在此方法中会创建ViewRootImpl的实例。
  7. 最终会调用ViewRootImpl的setView()方法加载DecorView,执行绘制流程。

到此,App便正式启动,UI渲染结束后便可以看到App的主界面。

img

参考文档: https://blog.csdn.net/yushuyou/article/details/128985837