在前文分析启动SystemServer流程可以知道在ZygoteInit中通过反射机制执行SystemServer的main函数,从而进入到SystemServer中。在SystemServer的main函数中所做的事情很简单,就是创建SystemServer对象并调用它的run函数进一步处理。
如果设备的时间为1970年之前的话,就会将手机时间设置为1970年。为SystemServer创建主线程的Looper,并且进入消息循环。加载一个叫做android_servers的本地库,它提供本地方法的接口。之后调用本地函数启动sensor service。为系统进行创建Context,创建SystemServiceManager进行管理系统服务。
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit(); //每次开机都会清理一下内存, 获取更多的内存空间
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); //内存使用相关
Build.ensureFingerprintProperty(); //指纹配置
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
BinderInternal.setMaxThreads(sMaxBinderThreads); //增加Binder数量
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND); //设置systemserver为前台进程
android.os.Process.setCanSelfBackground(false); //不能自己变为后台进程
Looper.prepareMainLooper(); //准备main looper
System.loadLibrary("android_servers"); //初始化本地的服务
performPendingShutdown(); //检查上次是否关机发生问题
createSystemContext(); //初始化上下文
以上处理完后就开始启动Java层的各个服务首先将一些比较重要并且比较复杂相互之间有依赖的服务统一启动,而大部分系统服务的启动是由SystemServiceManager进行统一管理,仍然基于反射等机制,根据启动类的class name进行创建类的实例。例如启动 PowerManagerService过程:
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
将PowerManagerService的class传递给SystemServiceManager从而启动PowerManagerService. 所要启动的类必须是SystemService的子类.
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName(); //获取class的name
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
Constr