private void run() {
//创建主线程Looper、ActivityThread、SystemContext
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 并行线程池
SystemServerInitThreadPool.get();
// Start services.
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
// Loop forever.
Looper.loop();
}
下面是一些主要的初始化方法。
/**
* 这些服务具有复杂的相互依赖关系,所以需要放一起全部初始化
*/
private void startBootstrapServices() {
// Start the watchdog as early as possible so we can crash the system server
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
//启动AMS
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//电源管理器需要提前启动,因为其他服务需要它
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// Start the package manager.
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
//设置Application实例并开始
mActivityManagerService.setSystemProcess();
//使用 ActivityManager 实例完成看门狗设置并监听重启
watchdog.init(context, mActivityManagerService);
}
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
*/
private void startOtherServices() {
//启动WMS
wm = WindowManagerService.main();
mActivityManagerService.setWindowManager(wm);
//WMS 显示默认启动消息
ActivityManagerNative.getDefault().showBootMessage();
//开始启动初始应用程序
mActivityManagerService.systemReady(new Runnable(){
//SystemUI
startSystemUi(context, windowManagerF);
});
}