SystemServer进程被创建后,主要做了如下工作:
1.启动Binder线程池,这样就可以与其他进程进行通信。
2.创建SystemServerManager,其用于对系统的服务进行创建、启动和生命周期管理。
3.启动各种系统服务。
关于第1点启动Binder线程池,再简述下,详细可查看我的上一篇:Android R开机流程跟踪-----Zygote进程和启动SystemServer进程
SystemServer流程:
main方法解析流程如下:
创建系统上下文context
private void createSystemContext() {
//创建systemserver进程的上下文信息
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
//设置主题
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//获取systemui上下文信息,并设置主题
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
创建SystemServiceManager
SystemServiceManager这个对象主要作用是用于创建和管理系统服务:
public class SystemServiceManager {
private static final String TAG = "SystemServiceManager";
private final Context mContext;
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
SystemServiceManager(Context context) {
mContext = context;
}
/*
* Loads and initializes a class from the given classLoader. Returns the class.
*/
@SuppressWarnings("unchecked")
private static Class<SystemService> loadClassFromLoader(String className,
ClassLoader classLoader) {
try {
return (Class<SystemService>) Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Failed to create service " + className
+ " from class loader " + classLoader.toString() + ": service class not "
+ "found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it. Also ensure that the correct path for the "
+ "classloader is supplied, if applicable.", ex);
}
}
/**
* 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.
*/
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
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 {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
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");
}
}
这个对象里面有一个mServices集合,这个集合主要保存的就是系统服务,可以看到,所有的系统服务都需要继承com.android.server.SystemService,并且通过反射的方式去实例化系统服务对象,最后会调用系统服务的onStart()方法,关于实例化的系统服务对象,可以过滤SystemServiceManager来查看打印的系统服务日志。
启动系统服务
分为三类,分批启动
startBootstrapServices(); // 启动引导服务
startCoreServices(); // 启动核心服务
startOtherServices(); // 启动其他服务
引导服务
private void startBootstrapServices() {
traceBeginAndSlog("StartWatchdog");
//启动watchdog
//尽早启动watchdog,如果在早起启动时发生死锁,我们可以让system_server崩溃,从而进行详细分析
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
traceEnd();
...
//阻塞等待installd完成启动,以便有机会创建具有适当权限的关键目录,如/data/user。
//我们需要在初始化其他服务之前完成此任务。
traceBeginAndSlog("StartInstaller");
Installer installer = mSystemServiceManager.startService(Installer.class);
traceEnd();
...
//启动服务ActivityManagerService,并为其设置mSystemServiceManager和installer
traceBeginAndSlog("StartActivityManager");
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
traceEnd();
//启动服务PowerManagerService
//Power manager需要尽早启动,因为其他服务需要它。
//本机守护进程可能正在监视它的注册,
//因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)。
traceBeginAndSlog("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();
...
//初始化power management
traceBeginAndSlog("InitPowerManagement");
mActivityManagerService.initPowerManagement();
traceEnd();
//启动recovery system,以防需要重新启动
traceBeginAndSlog("StartRecoverySystemService");
mSystemServiceManager.startService(RecoverySystemService.class);
traceEnd();
...
//启动服务LightsService
//管理led和显示背光,所以我们需要它来打开显示
traceBeginAndSlog("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
traceEnd();
...
//启动服务DisplayManagerService
//显示管理器需要在包管理器之前提供显示指标
traceBeginAndSlog("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
traceEnd();
//在初始化package manager之前,需要默认的显示.
traceBeginAndSlog("WaitForDisplay");
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
traceEnd();
//当设备正在加密时,仅运行核心
String cryptState = VoldProperties.decrypt().orElse("");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
...
//启动服务PackageManagerService
traceBeginAndSlog("StartPackageManagerService");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
...
//启动服务UserManagerService,新建目录/data/user/
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
traceEnd();
// Set up the Application instance for the system process and get started.
//为系统进程设置应用程序实例并开始。
//设置AMS
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
//使用一个ActivityManager实例完成watchdog设置并监听重启,
//只有在ActivityManagerService作为一个系统进程正确启动后才能这样做
traceBeginAndSlog("InitWatchdog");
watchdog.init(mSystemContext, mActivityManagerService);
traceEnd();
//传感器服务需要访问包管理器服务、app ops服务和权限服务,
//因此我们在它们之后启动它。
//在单独的线程中启动传感器服务。在使用它之前应该检查完成情况。
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_SENSOR_SERVICE);
startSensorService(); //启动传感器服务
traceLog.traceEnd();
}, START_SENSOR_SERVICE);
}
从这里可以看出,服务的创建基本都是通过SystemServiceManager的startService()进行创建的,PackageManagerService例外,它是直接调用它的main()方法。