一、应用程序进程创建
1、 应用进程请求
- Zygote进程会创建一个Socket,用来等待AMS请求创建应用进程。
- ActivityManagerService会通过调用startProcessLocked来发送请求。
- 接收到请求后,Zygote进程会fork自身创建应用进程。
2、接收创建请求
通过ZygoteServer的runSelectLoop方法处理创建进程的请求–>
ZygoteConnection的runOnce处理请求数据–>
ZygoteInit的zygoteInit方法中创建Binder线程池–>
RuntimeInit的invokeStaticMain方法
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
throws Zygote.MethodAndArgsCaller {
Class<?> cl;
try {
//通过反射创建了ActivityThread对象
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
//获取ActivityThread对象的main方法
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);
}
......
throw new Zygote.MethodAndArgsCaller(m, argv);
}
最后抛出一个MethodAndArgsCaller异常,被ZygoteInit的main方法处理–>
Zygote的run方法
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
通过反射调用了ActivityThread的main方法
3、ActivityThread
public static void main(String[] args) {
......
//创建Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//Looper开始处理消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}