继续上一篇Activity启动流程(上)
下面继续新activity的启动流程mStackSupervisor.startSpecificActivityLocked(next, true, true);
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java1
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
27void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// 获取要启动activity的进程信息
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
getLaunchTimeTracker().setLaunchTime(r);
//判断进程是否是null
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
}
//如果进程是null,告诉AMS启动进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
上面代码:判断要启动的activity的进程是否存在,如果存在就执行realStartActivityLocked方法,如果不存在就调用AMS的startProcessLocked方法创建新的进程。也就是说我们的app是否已经启动,如果启动了就执行realStartActivityLocked方法,如果没启动比如点击应手机用图标后,就执行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 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) {
app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
...
final boolean success = startProcessLocked(app, hostingType, hostingNameStr,
abiOverride);
...
return success ? app : null;
}
private final void startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr) {
startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */);
}
@GuardedBy("this")
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) {
......
final String entryPoint = "android.app.ActivityThread";
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);
}
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) {
//新进程的启动过程是否需要异步执行(默认值为true)
if (mConstants.FLAG_PROCESS_START_ASYNC) {
...
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);
}
...
}else{
...
final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
invokeWith, startTime);
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
...
}
return app.pid > 0;
}
上面的代码经过一系列的startProcessLocked的重载方法的调用,最后调用到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
28private 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 {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
app.processName);
checkTime(startTime, "startProcess: asking zygote to start proc");
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});
}
checkTime(startTime, "startProcess: returned from zygote!");
return startResult;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}
hostingType代表我们是使用何种方式启动的,我们这里不是webview_service,所以走else中的方法Process.start
/frameworks/base/core/java/android/os/Process.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public 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);
}
start方法通过Socket通信,把新进程的创建请求交给zygote进程处理。zygoteProcess是ZygoteProcess对象/frameworks/base/core/java/android/os/ZygoteProcess.java1
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 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) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
throw new RuntimeException(
"Starting VM process through Zygote failed", ex);
}
}
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 {
synchronized(mLock) {
......
//计算并配置启动进程的各种参数,之后调用下面方法
//第一个参数根据abi来选择跟32位的zygote还是64位的zygote进程通信
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
}
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();
// Should there be a timeout on this?
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);
}
}
}
到这里result.pid = inputStream.readInt() 新进程创建成功并返回该进程就有了它自己的pid,下面就是这个新的应用进程启动activity
上面的方法我们知道了最终创建了一个新的进程并返回了新进程的pid,那么这个新的进程到底是怎么创建的呢
看一下上面startViaZygote这个方法调用zygoteSendArgsAndGetResult方法传入的第一个参数openZygoteSocketIfNeeded(abi),这里是根据不同的cpu开启socket通信。也就是说AMS是通过socket跟zygote进程通信的。
看一下Process类的几个成员变量
/frameworks/base/core/java/android/os/Process.java1
2
3
4
5
6
7
8
9
10
11
12
13
14public class Process {
...
public static final String ZYGOTE_SOCKET = "zygote";
public static final String SECONDARY_ZYGOTE_SOCKET = "zygote_secondary";
...
public static final ZygoteProcess zygoteProcess =
new ZygoteProcess(ZYGOTE_SOCKET, SECONDARY_ZYGOTE_SOCKET);
....
}
public ZygoteProcess(LocalSocketAddress primarySocket, LocalSocketAddress secondarySocket) {
mSocket = primarySocket;
mSecondarySocket = secondarySocket;
}
上面是两个socket服务,先连接第一个连不上在连接第二个尽可能保证服务正常
然后看openZygoteSocketIfNeeded(abi)是怎连接socket的1
2
3
4
5
6
7
8private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
...
primaryZygoteState = ZygoteState.connect(mSocket);
...
secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
}
ZygoteState是ZygoteProcess的一个内部类/frameworks/base/core/java/android/os/ZygoteProcess.java 看起静态连接方法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
27public 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);
Log.i("Zygote", "Process: zygote socket " + address.getNamespace() + "/"
+ address.getName() + " opened, supported ABIS: " + abiListString);
return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
Arrays.asList(abiListString.split(",")));
通过LocalSocket来连接zygote或者zygote_secondary进程,写出流zygoteWriter
然后回到前面的zygoteSendArgsAndGetResult方法,通过写出流将要创建的信息发送给zygote进程。
那zygote进程是怎么接收这个信息的呢,在Android系统中,所有的应用程序进程以及系统服务进程SystemServer都是由Zygote进程孕育(fork)出来的
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
Zygote进程在启动的时候,在其main方法中会调用其forkSystemServer方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
...
final Runnable caller;
...
Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
...
caller = zygoteServer.runSelectLoop(abiList);
if (caller != null) {
caller.run();
}
}
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
...
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}
在创建system_sever的时候会执行waitForSecondaryZygote方法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 private static void waitForSecondaryZygote(String socketName) {
String otherZygoteName = Process.ZYGOTE_SOCKET.equals(socketName) ?
Process.SECONDARY_ZYGOTE_SOCKET : Process.ZYGOTE_SOCKET;
ZygoteProcess.waitForConnectionToZygote(otherZygoteName);
}
/frameworks/base/core/java/android/os/ZygoteProcess.java
public static void waitForConnectionToZygote(String socketName) {
final LocalSocketAddress address =
new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.RESERVED);
waitForConnectionToZygote(address);
}
//尝试连接Zygote 进程直到超时
public static void waitForConnectionToZygote(LocalSocketAddress address) {
for (int n = 20; n >= 0; n--) {
try {
final ZygoteState zs = ZygoteState.connect(address);
zs.close();
return;
} catch (IOException ioe) {}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
可以看到它也会连接到这个socket上,这样就可以跟客户端通信了,在回到上面的main方法中,caller = zygoteServer.runSelectLoop(abiList)
caller是一个Runnable,执行它的run方法。其实就是在一个子线程中等待接收客户端发来的信息。
1 | Runnable runSelectLoop(String abiList) { |
当pid=0的时候,就是在当前新建的进程中执行1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22private Runnable handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors,
FileDescriptor pipeFd, boolean isZygote) {
...
if (parsedArgs.invokeWith != null) {
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
VMRuntime.getCurrentInstructionSet(),
pipeFd, parsedArgs.remainingArgs);
// Should not get here.
throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
} else {
if (!isZygote) {//是否启动zygote的子进程这里是false
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs,
null /* classLoader */);
} else {
return ZygoteInit.childZygoteInit(parsedArgs.targetSdkVersion,
parsedArgs.remainingArgs, null /* classLoader */);
}
}
...
}
这里没有传入没有传入–invoke-with,所以走else,是否启动zygote的子进程这里是false所以走ZygoteInit.zygoteInit1
2
3
4
5
6
7
8
9
10
11
12public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
返回了RuntimeInit.applicationInit方法,传入sdk的版本,各种参数和类加载器classloader1
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
45protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
nativeSetExitWithoutCleanup(true);
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
final Arguments args = new Arguments(argv);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
return new MethodAndArgsCaller(m, argv);
}
这里的className是在上面的ActivityManagerService中的startProcessLocked方法entryPoint一步一步传过来的final String entryPoint = "android.app.ActivityThread";
所以这里通过反射创建了ActivityThread类并执行其main方法
/frameworks/base/core/java/android/app/ActivityThread.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
...
//为主线程创建一个消息循环对象
Looper.prepareMainLooper();
...
ActivityThread thread = new ActivityThread();
//绑定应用程序
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//启动消息循环
Looper.loop();
}
创建主线程的Looper对象,绑定应用程序,启动Looper1
2
3
4
5
6
7
8private void attach(boolean system, long startSeq) {
...
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
}
...
}
ActivityManager.getService()返回的是IActivityManager的binder代理对象,用于应用进程向AMS通信
mgr这个代理对象通过AIDL调用AMS中的attachApplication方法,mAppThread就是需要为应用绑定的ApplicationThread对象
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java1
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 public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
...
if (app.isolatedEntryPoint != null) {
thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
} else if (app.instr != null) {
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
} else {
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);
}
...
//检查当前栈顶的activity是否满足要启动的activity
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
...
}
app.isolatedEntryPoint
很明显我们不是一个隔离的进程,我们是为了创建activity所有走else方法,最终都会进入 thread.bindApplication
thread是IApplicationThread的binder对象,也就是AMS通过AIDL调用应用进程的ApplicationThread方法。所以说AMS不直接参与Application的初始化流程,而是配置一些参数之后交给应用自己处理
mStackSupervisor.attachApplicationLocked(app)检查当前栈顶的activity是否是要启动的activity
先看bindApplication方法,这个就是初始化Application
/frameworks/base/core/java/android/app/ActivityThread.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public 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) {
...
sendMessage(H.BIND_APPLICATION, data);
}
class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
}
}
这里跟前面暂停一个activity一样,发从一个消息,然后去H这个Handler中执行
1 | private void handleBindApplication(AppBindData data) { |
上面最终执行了Application的onCreate方法
在回到attachApplicationLocked中看mStackSupervisor.attachApplicationLocked(app)方法
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
...
stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
...
//需要启动的Activity
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
//遍历所有的activity
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 {
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {
didSomething = true;
}
} catch (RemoteException e) {
throw e;
}
}
}
...
}
这里又看到了realStartActivityLocked这个方法,很熟悉吧,我们在前面startSpecificActivityLocked方法中判断要启动的activity的进程是否存在,如果存在就执行realStartActivityLocked方法,如果不存在就调用AMS的startProcessLocked方法创建新的进程,所以这里我们转了一圈启动了进程之后又回到realStartActivityLocked这个方法来真正的启动一个activity。
/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java1
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
28final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
// 为Activity的launch创建 transaction
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
//创建一个LaunchActivityItem对象,并传添加到事物中
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));
//设置Activity的最终状态
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
......
}
创建一个LaunchActivityItem对象,并传添加到事物中,这里跟前面的pause的流程一样,添加到事物中后,通过ClientLifecycleManager 执行事物。通过ClientLifecycleManager中的scheduleTransaction方法跟前面pause中的是一样的,就不贴出来了。
大体流程就是最后执行到IApplicationThread中的scheduleTransaction方法,又回到ActivityThread中,也就是AMS交给应用进程自己创建activity自己创建,scheduleTransaction中发从了一个message交给H这个handler处理。最终执行到TransactionExecutor中的execute方法
上面代码中clientTransaction.addCallback中传入的是LaunchActivityItem.obtain方法,它返回了一个addCallback中传入的是LaunchActivityItem对象
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java1
2
3
4
5
6
7
8
9
10public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
因为前面代码是addCallback,所以这里执行executeCallbacks方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public void executeCallbacks(ClientTransaction transaction) {
//通过前面传的我们知道ClientTransactionItem就是是LaunchActivityItem
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null) {
return;
}
....
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
......
}
}
首先获得callback然后执行callback的execute方法。这里的callback是LaunchActivityItem对象,LaunchActivityItem只实现了ClientTransactionItem中的execute方法,所以不执行postExecute
/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java1
2
3
4
5
6
7
8
9
10public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
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 */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
可以看到这里封装了一个activity客户端记录类,然后执行ClientTransactionHandler中的handleLaunchActivity方法,ClientTransactionHandler 是一个抽象类,ActivityThread继承了它,所以其实又回到了ActivityThread中
1 | public Activity handleLaunchActivity(ActivityClientRecord r, |
这里初始化窗口管理器WindowManagerService之后,执行performLaunchActivity方法创建一个activity1
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
37private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
//ContextImpl类继承自Context抽象类,
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {...}
...
//检查Application是否存在如果不存在尝试创建
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
...
//把ContextImpl的成员变量mOuterContext赋值成activity
appContext.setOuterContext(activity);
//完成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);
...
//要启动的activity是不是持久的,对应Manifest中Application标签的android:persistent属性
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//设置 Activity 当前状态为 ON_CREATE
r.setState(ON_CREATE);
}
拿到类加载器ClassLoader然后委托给mInstrumentation去创建activity,然后初始化成员变量,最后走到mInstrumentation.callActivityOnCreate方法1
2
3
4
5public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
执行activity的performCreate方法
/frameworks/base/core/java/android/app/Activity.java1
2
3
4
5
6
7
8
9
10
11
12final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
...
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
...
}
到这里终于看到了我们熟悉的onCreate方法啦!!!别着急还没完呢
回到上面realStartActivityLocked方法中,我们传入的第二个参数是top == activity,很明显最顶层的就是我们要启动的activity,所以这里是true,所以lifecycleItem = ResumeActivityItem.obtain,然后执行了 clientTransaction.setLifecycleStateRequest(lifecycleItem);方法。所以我们上面TransactionExecutor类中的execute方法中的executeLifecycleState(transaction)方法也会执行1
2
3
4
5
6
7
8
9
10public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null) {
return;
}
...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
最终会执行ResumeActivityItem中的execute方法1
2
3
4
5
6
7public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
跟上面思路一样一样回到ActivityThread中执行handleResumeActivity方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
...
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
...
final Activity a = r.activity;
...
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
...
a.mWindowAdded = true;
wm.addView(decor, l);
...
Looper.myQueue().addIdleHandler(new Idler());
}
performResumeActivity就是去执行activity的onResume方法,然后创建WindowManager,把DecorView方法WindowManager中。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason) {
...
r.activity.performResume(r.startsNotResumed, reason);
r.state = null;
r.persistentState = null;
r.setState(ON_RESUME);
...
}
/frameworks/base/core/java/android/app/Activity.java
final void performResume(boolean followedByPause, String reason) {
//判断是不是restart
performRestart(true /* start */, reason);
...
mInstrumentation.callActivityOnResume(this);
...
}
/frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
activity.onResume();
...
}
看到了onResume,至此activity终于启动完成。
下面总结一下:
- 在我们调用startActivity或者startActityForResult方法的时候,通过Binder通信向ActivityManagerService发送Activity的启动请求
- ActivityManagerService收到请求之后,进行合法检测和根据activity的启动模式进行一系列的初始化和准备工作
- ActivityManagerService判断当前栈顶的activity是否能够复用,如果能复用并且启动模式为复用栈顶,就通知栈顶activity所在进程回调onNewIntent()
- 如果不能复用,那么通过Binder通知栈顶的activity执行onPause操作
- 栈顶的activity执行完onPause之后,开始启动将目标activity,判断目标activity所在进程是否已经启动,如果已经启动,则去执行目标activity的生命周期方法
- 如果目标activity所在进程没有启动,则通过Socket通知Zygote进程fork出一个新的进程,然后通过传过去的“android.app.ActivityThread”字符串反射出ActivityThread对象,并执行它的main方法初始化主线程。
- 新进程中的activity依次调用onCreate->onStart->onResume方法来完成activity的启动流程。
参考连接:
https://blog.csdn.net/hongchi110/article/details/82890180#ch2-5
https://blog.csdn.net/cjh_android/article/details/82533321
https://blog.csdn.net/lj19851227/article/details/82562115