SystemServer进程主要用于创建系统服务,我们熟知的AMS、WMS和PMS都是由它创建的。
SystemServer由Zygote进程启动,具体在ZygoteInit.java的forkSystemServer方法中fork了SystemServer进程。
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
//...
//当前运行在SystemServer进程中
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
//关闭Zygote进程创建的Socket
//SystemServer进程复制了Zygote进程的地址空间,因此也会得到Zygote进程创建的Socket。
//这个Socket对于SystemServer进程没有用处,所以关闭了Socket
zygoteServer.closeServerSocket();
//启动SystemServer进程
return handleSystemServerProcess(parsedArgs);
}
return null;
}
可以看到这里调用了handleSystemServerProcess,我们再来看handleSystemServerProcess()
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
//...
if (parsedArgs.invokeWith != null) {
//...
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
//创建PathClassLoader
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
//调用ZygoteInit.zygoteInit()方法
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}
创建了PathClassLoader字后,又调用了ZygoteInit.zygoteInit,再来看下ZygoteInit#zygoteInit()
public 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();
//启动Binder线程池
ZygoteInit.nativeZygoteInit();
//进入SystemServer的main方法
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
这里调用了 ZygoteInit.nativeZygoteInit()
和 RuntimeInit.applicationInit()
,我们分别来看下
启动Binder线程池
ZygoteInit.nativeZygoteInit()
是一个Native方法,我们先来看下它对应的JNI文件
extern int register_com_android_internal_os_ZygoteInit(JNIEnv *env);
int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
const JNINativeMethod methods[] = {
{ "nativeZygoteInit", "()V",
(void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
};
return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
methods, NELEM(methods));
}
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit(); //gCurRuntime是AndroidRuntime类型的指针,具体指向其子类AppRuntime
}
在来看下AppRuntime的onZygoteInit方法frameworks/base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool(); //启动一个Binder线程池
}
这里会启动一个Binder线程池,这样SystemServer进程就可以使用Binder与其他进程进行通讯了。
看到这里,我们知道RuntimeInit.java的nativeZygoteInit函数主要是用来启动Binder线程池的。
进入SystemServer的main方法
我们再回到RuntimeInit.java的代码,看下RuntimeInit.applicationInit()
的内部frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
//...
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
protected 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 {
//找到SystemServer的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);
}
//...
//将找到的main方法传入MethodAndArgsCaller并返回,最终会抛出该异常
//这种抛出异常的处理会清除所有的设置过程需要的堆栈帧,并让SystemServer的main方法看起来像是SystemServer进程的入口方法
return new MethodAndArgsCaller(m, argv);
}
static class MethodAndArgsCaller implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
try {
//mMethod就是SystemServer的main方法,调用mMethod的invoke()之后,
//SystemServer的main方法就会被动态调用,SystemServer进程就进入SystemServer的main方法中
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);
}
}
}
再来看下在ZygoteInit.java的main方法中时如何捕获MethodAndArgsCaller异常的
public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
//...
final Runnable caller;
try {
//...
caller = zygoteServer.runSelectLoop(abiList);
} catch (Throwable ex) {
Log.e(TAG, "System zygote died with exception", ex);
throw ex;
} finally {
zygoteServer.closeServerSocket();
}
if (caller != null) {
//当caller不为null,则调用caller的run方法,caller是MethodAndArgsCaller
caller.run();
}
}
解析SystemServer进程
接着,我们就可以来看SystemServer的main方法了
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
try {
//...
//创建消息Looper
Looper.prepareMainLooper();
//...
//加载了动态库libandroid_servers.so
System.loadLibrary("android_servers");
performPendingShutdown();
//创建系统的Context
createSystemContext();
//创建SystemServerManager,它会对系统服务进行创建、启动和生命周期管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
try {
traceBeginAndSlog("StartServices");
//启动引导服务
//SystermServiceManager启动了ActivityManagerService、PowerManagerService、PackageManagerService等服务
startBootstrapServices();
//启动核心服务
//启动了DropBoxManagerService、BatteryService、UsageStatsService和WebViewUpdateService
startCoreServices();
//启动其他服务
//启动了CameraService、AlarmManagerService、VrManagerService等服务
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
//...
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看到,SystemServer.run中,启动了各种服务,这些服务都是SystemService的子类。
官方把系统服务分为了三种类型,分别是引导服务、核心服务和其他服务。
其他服务是一些非紧要和不需要立即启动的服务,这些服务一共有100多个。
这些系统服务启动的逻辑是相似的,这里以启动PowerManagerService来进行举例。
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
来看mSystemServiceManager.startService,frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public void startService(@NonNull final SystemService service) {
//注册Service,将Service添加到mServices中
mServices.add(service);
long time = SystemClock.elapsedRealtime();
try {
//启动Service,调用service的onStart方法
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
这样就完成了PowerManagerService的启动。
除了通过mSystemServiceManager.startService()的方式来启动系统服务外,也可以通过比如PackageManagerService.main的方式来启动系统服务,内部是通过调用SystemManager来注册。
SystemManager用来管理系统中的各种Service,用于系统C/S架构中的Binder通讯机制 : Client端要使用某个Service,则需要先到ServiceManager查询Service的相关新,然后根据Service的相关信息与Service所在的Server进程建立通信,这样Client端就可以使用Service了。
SystemServer小结
SystemServer进程被创建后,主要做了如下的工作
- 启动Binder线程池,这样就可以与其他进程进行通讯
- 创建SystemServiceManager,其用于对系统的服务进行创建、启动和生命周期管理
- 启动各种系统服务