主要分析一下SystemServer启动过后的内部逻辑,特别说明一下AMS,WMS都属于SystemServer进程,属于同一个进程

一. SystemServer进程启动流程

基于Android13的系统启动流程分析(五)之Zygote和SystemServer启动流程这篇文章有详细讲解,这里再简单的过一下如何启动的SystemServer

在zygote进程创建过后,会调用forkSystemServer()来孵化出SystemServer进程,当前该进程创建成功后会反射调用到SystemServer.java的main函数,从而启动完成SystemServer

二. SystemServer主函数分析

main函数会被ZygoteInit的子方法handleSystemServerProcess反射调用到
frameworks/base/services/java/com/android/server/SystemServer.java

public static void main(String[] args) {
        new SystemServer().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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
private void run() {
...
try {
...
// 设置系统语言,国家,时区相关
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
...
// Prepare the main looper thread (this thread).
// 设置main线程的优先级,有此可得主线程就是:SystemServer进程下的其中线程
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
// 开始主线程的运行,和Looper.loop配对使用
// 运行在 Looper.prepareMainLooper()~Looper.loop()
// 之间的就是运行在主线程中
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
...
// 初始化native services,加载android_servers库(libandroid_servers.so)
System.loadLibrary("android_servers");
...
// 通过ActivityThread来创建system上下文
createSystemContext();

// Call per-process mainline module initialization.
// 初始化ActivityThread
// 创建TelephonyServiceManager,StatsServiceManager,MediaServiceManager
ActivityThread.initializeMainlineModules();

// 将SystemServer加入ServiceManager(binder线程池)
// 每个继承自SystemServer 或属于SystemServer进程的服务都将加入到
// ServiceManager中的线程池中
ServiceManager.addService("system_server_dumper", mDumper);
mDumper.addDumpable(this);

// 每个server基本上对应了一个manager,对外提供的API也是只能获取到manager
// 创建SystemServiceManager,它会对系统的服务进行创建、启动和生命周期管理,启动系统的各种服务
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
mDumper.addDumpable(mSystemServiceManager);
// LocalServices是system_server进程中各个服务提供的本地服务
// system_server进程中每个服务都可以往LocalServices放对象
// 有些核心服务是继承自SystemServer,LocalServices是公开缓存池目的是:解耦
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
...
// Start services.
try {
t.traceBegin("StartServices");
// 启动系统启动所需的一系列关键服务:AMS,P(power/package)MS,SensorService,DisplayManagerService,LightService等
startBootstrapServices(t);
// 启动核心服务:BatteryService,GpuService等
startCoreServices(t);
// 启动其他服务:VibratorManagerService,闹钟服务,相机服务,网络服务,输入法服务,存储服务等
startOtherServices(t);
// 以上的所有服务都由mSystemServiceManager来启动,所以都是继承自SystemServer
// 分别是引导服务、核心服务和其他服务
// [引导服务]
// Installer 系统安装apk时的一个服务类,启动完成Installer服务之后才能启动其他的系统服务
//ActivityManagerService 负责四大组件的启动、切换、调度。
//PowerManagerService 计算系统中和Power相关的计算,然后决策系统应该如何反应
//LightsService 管理和显示背光LED
//DisplayManagerService 用来管理所有显示设备
//UserManagerService 多用户模式管理
//SensorService 为系统提供各种感应器服务
//PackageManagerService 用来对apk进行安装、解析、删除、卸载等等操作
// [核心服务]
//BatteryService 管理电池相关的服务
//UsageStatsService 收集用户使用每一个APP的频率、使用时常
//WebViewUpdateService WebView更新服务
// [其他服务]
//CameraService 摄像头相关服务
//AlarmManagerService 全局定时器管理服务
//InputManagerService 管理输入事件
//WindowManagerService 窗口管理服务
//VrManagerService VR模式管理服务
//BluetoothService 蓝牙管理服务
//NotificationManagerService 通知管理服务
//DeviceStorageMonitorService 存储相关管理服务
//LocationManagerService 定位管理服务
//AudioService 音频相关管理服务
} catch (Throwable ex) {
...
} finally {
...
}

...
Looper.loop();// 主线程
// 若执行到这里说明主线程意外退出了
// 主线程:Looper.prepareMainlooper~ Looper.loop之间
throw new RuntimeException("Main thread loop unexpectedly exited");
}

以上方法可以看出来关于其他服务的启动都是运行在主线程中的Looper.prepareMainlooper~ Looper.loop之间,每个SystemServer中的服务都有一个binder,会加入到ServiceManager的binder线程池中统一管理,这样拿到全局的ServiceManager,根据AIDL 获取到每Service了

  • startBootstrapServices(t)
    启动系统启动所需的一系列关键服务:
    AMS,P(power/package)MS,SensorService,DisplayManagerService,LightService等
  • startCoreServices(t)
    启动核心服务:BatteryService,GpuService等
  • startOtherServices(t)
    启动其他服务:VibratorManagerService,闹钟服务,相机服务,网络服务,输入法服务,存储服务等

在这些启动的服务里(调用了onStart启动服务),都会将服务存入ServiceManager 用来管理系统中的各种Service,用于系统C/S架构中的Binder机制通信:Client端要使用某个Service,则需要先到ServiceManager查询Service的相关信息,然后根据Service的相关信息与Service所在的Server进程建立通讯通路,这样Client端就可以使用Service了

image-20231129172417054

image-20231129172431908

1. startBootstrapServices

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
  private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
// 尽早启动看门狗,以便在早期启动过程中出现死锁时使系统服务器崩溃
t.traceBegin("StartWatchdog");
// 启动看门狗,看门狗需要定时喂狗,若喂狗超时则会触发重启,以便知道进程和服务是否正常运行
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
t.traceEnd();
...
t.traceBegin("StartInstaller");
// 通过mSystemServiceManager来启动Installer服务,管理应用的安装与卸载
Installer installer = mSystemServiceManager.startService(Installer.class);
t.traceEnd();
...
// 通过mSystemServiceManager来启动UriGrantsManagerService,管理Uri
t.traceBegin("UriGrantsManagerService");
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
t.traceEnd();

// 通过mSystemServiceManager来启动PowerStatsService,管理电源状态
t.traceBegin("StartPowerStatsService");
mSystemServiceManager.startService(PowerStatsService.class);
t.traceEnd();
...
t.traceBegin("StartActivityManager");
// 通过mSystemServiceManager来启动ActivityTaskManagerService,管理Activity任务栈
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
// 启动ActivityManagerService,管理Activity等
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
// 让ActivityManagerService拿到systemServer,例如可以通过mSystemServiceManager来判断系统是否启动完成
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();

...
// 启用PowerManagerService服务,电源管理服务
t.traceBegin("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
t.traceEnd();
...
// 启动屏幕亮度服务,比如亮度调整
t.traceBegin("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
t.traceEnd();

// 启动屏幕显示服务
t.traceBegin("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
t.traceEnd();

...
// 启动PMS,包管理服务
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
domainVerificationService, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF,
mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}

...
// 启动传感器服务
t.traceBegin("StartSensorService");
mSystemServiceManager.startService(SensorService.class);
t.traceEnd();
t.traceEnd(); // startBootstrapServices
}

可以看到大多数服务都是通过mSystemServiceManager.startService来启动,核心服务和其他服务都是一样的,就不过多分析了
可以先看看startService方法内容

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
 public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
...
final T service;
try {
// 反射拿到该java类
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} ...
// 将当前服务(java类)加入SystemService服务队列中,统一管理
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}

public void startService(@NonNull final SystemService service) {
// 将当前服务加入mServices队列中
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
// 调用当前服务的onStart来启动服务
service.onStart();
} catch (RuntimeException ex) {
...
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

可以看到startService方法就是反射拿到服务类,然后加入队列中,调用其onStart方法进行启动

2. ServiceManager服务管理

每个属于SystemServer的服务都将加入到ServiceManager的binder线程池中,以供后续直接获取和管理
就拿BatteryService服务来讲解

1
mSystemServiceManager.startService(BatteryService.class);

已知startService后会调用BatteryService服务的onStart方法,继续看看onStart内部

1
2
3
4
5
6
7
8
9
10
11
12
@Override
public void onStart() {
...
mBinderService = new BinderService();
// 将BinderService服务加入ServiceManager中
publishBinderService("battery", mBinderService);
mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
// 将batteryproperties服务加入ServiceManager中
publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
// 将BinderService服务加入到LocalServices中
publishLocalService(BatteryManagerInternal.class, new LocalService());
}

继续看看mBinderService具体是什么,又是如何加入到ServiceManager中的

1
2
3
private final class BinderService extends Binder {
...
}

可以看到mBinderService就是一个Binder,然后调用publishBinderService加入到ServiceManager中的binder线程池中

1
2
3
protected final void publishBinderService(...) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}

调用ServiceManager.addService加入到binder线程池中(ServiceManager暂不深究,只知其内部维护了binder线程池),而ServiceManager服务早就在rc文件中作为核心服务启动了,所以具体实现都是c++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
service servicemanager /system/bin/servicemanager
class core animation
user system
group system readproc
critical
onrestart restart apexd
onrestart restart audioserver
onrestart restart gatekeeperd
onrestart class_restart main
onrestart class_restart hal
onrestart class_restart early_hal
writepid /dev/cpuset/system-background/tasks
shutdown critical

三. 总结

其实SystemServer是通过init fork出来的,父进程就是zygote,而zygote父进程就是init进程。
SystemServer内部逻辑主要就是创建了核心服务,引导服务,其他服务,例如WMS,PMS,电池服务,蓝牙服务等。这些服务都不是单独的进程,而是都属于SystemServer进程,启动这些服务过后会将这些服务加入ServiceManager的binder线程池中,因为这些服务内部都创建了Binder实例,再加入到了ServiceManager的binder线程池中,以便与随时获取服务与只通信

参考文章:Android系统启动流程(三)解析SyetemServer进程启动过程