Zygote 进程通过 fork() 创建出 SystemServer,SystemServer进程继承了 Zygote 进程所有状态
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//...
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.debugFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
//关闭 Zygote 创建出来的 Socket
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs);
}
return null;
}
当 pid == 0 时,表示在子进程,也就是 SystemServer 进程,这里先关闭 Socket,再启动 SystemServer 进程。
handleSystemServerProcess
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
//参数判断
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
//创建 ClassLoader
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}
这里进行参数判断,如果参数正确,通过 createPathClassLoader 创建 class 解析器 ClassLoader,接着调用 ZygoteInit#zygoteInit,而 zygoteInit 仅仅是调用到了 native 层代码,之后调用 RuntimeInit#applicationInit
zygoteInit
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
//...
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
private static final native void nativeZygoteInit();
nativeZygoteInit
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit();
}
gCurRuntime 是 AndroidRuntime 在 native 层的指针,它在app_main.cpp 中定义
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
这里可参考 源码解读Binder机制 等四篇文章了解 binder 机制
applicationInit 方法主要调用了 findStaticMain 方法,返回一个 Runnable(部分版本是抛出异常,对异常捕获进行处理)
private static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
//通过反射得到 SystemServer
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
//找到 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);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
//返回一个 MethodAndArgsCaller 的 Runnable
return new MethodAndArgsCaller(m, argv);
}
这里传入的 className 为 args.startClass,即 com.android.server.SystemServer,通过反射组装成一个 Runnable 返回。
Runnable 在 Zygote 进程的 main 函数中执行 r.run(),接下来就看下 MethodAndArgsCaller 的 run 方法。
static class MethodAndArgsCaller implements Runnable {
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);
}
}
}
这里 mMethod 就是反射得到的 main 函数。
进入 SystemServer 的 main 函数(frameworks/base/services/java/com/android/server/SystemServer.java)
public static void main(String[] args) {
new SystemServer().run();
}
SystemServer 的 run
private void run() {
try {
//...
//设置线程
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
//创建主进程(SystemServer进程)消息Looper
Looper.prepareMainLooper();
// 加载动态库
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
//创建 Context
createSystemContext();
//创建 SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
}
// Start services.
try {
traceBeginAndSlog("StartServices");
//启动引导服务
startBootstrapServices();
//启动核心服务
startCoreServices();
//启动其他服务
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
// loop 循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
代码中都有标注,与 Application 启动流程大致类似,这里重点时最后三个 start 开头的方法,是 SystemServer 的重要作用。
SystemServiceManager
public class SystemServiceManager {
SystemServiceManager(Context context) {
mContext = context;
}
}
它的 startService 有很多重载
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
//反射得到此类
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
}
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
startService(service);
return service;
} finally {
}
}
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
public void startService(@NonNull final SystemService service) {
//添加到 mServices 列表中
mServices.add(service);
try {
//启动Service
service.onStart();
} catch (RuntimeException ex) {
}
}
此方法,与创建 SystemServer 异曲同工,SystemServer 就创建完成。