圖例只描述了Activity組件在進(jìn)程外的啟動過程勇皇,即從Launcher點(diǎn)擊圖標(biāo)啟動MainActivity的過程。
MainActivity的啟動過程涉及到了三個進(jìn)程。MainActivity組件、LauncherActivity組件和ActivityManagerService組件分別運(yùn)行在不同的進(jìn)程中。
在第23步中會首先創(chuàng)建進(jìn)程易阳,流程如下圖
其中ActivityManagerService和Process運(yùn)行在system_server進(jìn)程中,啟動新的進(jìn)程時吃粒,需要system_server與zygote進(jìn)程進(jìn)行socket通信潦俺,從而fork出新的進(jìn)程。執(zhí)行RuntimeInit.zygoteInit() -> RuntimeInit.applicationInit() -> RuntimeInit.invokeStaticMain()
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
redirectLogStreams();
commonInit();
nativeZygoteInit();
applicationInit(targetSdkVersion, argv, classLoader);
}
**RuntimeInit.invokeStaticMain()**
//className的值是“android.app.ActivityThread”
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
......
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
......
} catch (SecurityException ex) {
......
}
......
/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
注意
ActivityThread.main方法的執(zhí)行是通過拋異常的方式執(zhí)行的徐勃。拋出MethodAndrArgsCaller異常事示,一直按照原路向上拋。在ZygoteInit.main方法中捕獲異常僻肖,并調(diào)用run方法反射執(zhí)行ActivityThread.main方法
public class ZygoteInit {
public static void main(String argv[]) {
try {
......
registerZygoteSocket(socketName);
......
preload();
......
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
runSelectLoop(abiList);
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
// 處理異常
caller.run();
} catch (RuntimeException ex) {
Log.e(TAG, "Zygote died with exception", ex);
closeServerSocket();
throw ex;
}
}
}