Android 系统开机流程简析

1. 系统启动

1.1 主函数

Android 系统的开机过程中,第一个真正被实例化并执行的 Java 类就是 com.android.server.SystemServer,入口从类的主函数开始:

1
2
3
4
5
6
public final class SystemServer {
public static void main(String[] args) {
new SystemServer().run();
}
...
}

1.2 run() 方法

run() 方法中做了许多事,主要就是启动系统的相关服务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
private void run() {
// 初始化默认时间
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
// 初始化地区和语言
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
...
SystemProperties.set("persist.sys.locale", languageTag);
...
}
// 设置 Runtime 库
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

// 启用 SamplingProfilerIntegration
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}

// SystemServer 作为长期运行的系统组件,需要获取更大的虚拟机内存
VMRuntime.getRuntime().clearGrowthLimit();
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

// 初始化指纹识别
Build.ensureFingerprintProperty();

// 授予执行权限
Environment.setUserRequired(true);

// 确保 Binder 工作在前台
BinderInternal.disableBackgroundScheduling(true);

// 准备 Looper
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();

// 加载 so 库
System.loadLibrary("android_servers");

// 检查上次关机是否为意外关机
performPendingShutdown();

// 初始化系统的 Context
createSystemContext();

// 创建 SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext); // 管理系统服务(如启动系统服务)的 ServiceManager
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// 启动必要的服务 如 ServiceManager
try {
startBootstrapServices(); // AMS、PMS、Sensor
startCoreServices(); // 电量、使用情况统计等
startOtherServices(); // 电话、闹钟、网络、相机、输入法等
} catch (Throwable ex) {
...
}

...
// Looper 工作
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

1.3 AMS 与 PMS

run() 方法中调用了 startBootstrapServices() 方法,看看它是如何初始化 AMSPMS 的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void startBootstrapServices() {
// 初始化应用安装服务
Installer installer = mSystemServiceManager.startService(Installer.class);

// 启动 ActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
// 为 AMS 填充 SystemServiceManager
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
// 为 AMS 填充 Installer
mActivityManagerService.setInstaller(installer);

// 电源管理服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
...
// 创建 PMS 实例,并将它加入 ServerManager
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
// 将包括 AMS 在内等服务加入 ServiceManager
mActivityManagerService.setSystemProcess();
// 启动传感器服务
startSensorService();
}

1.4 启动不忘注册

ActivityManagerService 的启动中,调用的是 SystemServiceManager#startService() 方法,而这个方法中会默认注册该服务到 SystemServiceManager 中存储着以备不时之需:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public <T extends SystemService> T startService(Class<T> serviceClass) {
...
final T service;
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);

// 先注册到 mServices: ArrayList<SystemService>
mServices.add(service);

// 再启动它
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + name
+ ": onStart threw an exception", ex);
}
return service;
}

1.5 注册到 ServiceManager

仅注册到 SystemServiceManager 是不够的,还得注册到 ServiceManager 这个全局通讯录中:

1
2
3
4
5
6
7
8
9
10
11
public void setSystemProcess() {
try {
// 注册 AMS 服务
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
// 其它服务
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
...
}