Skytoby

Android系统SystemServer启动(下)

Android系统SystemServer启动(下)

基于Android10.0,分析SystemServer启动

一、SystemServer启动

上一节中讲到了从开机到SystemServer中main方法的启动过程,下面将介绍下SystemServer中的main方法,该方法主要执行的主要流程如下:

1
2
3
4
5
6
7
SystemServer.main
SystemServer.run
performPendingShutdown
createSystemContext
startBootstrapServices
startCoreServices
startOtherServices

1.1 SystemServer.main

1
2
3
4
5
6
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}

1.2 SystemServer.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
//如果系统时间是1970之前,则将系统时间设置为1970
// If a device's clock is before 1970 (before 0), a lot of
// APIs crash dealing with negative numbers, notably
// java.io.File#setLastModified, so instead we fake it and
// hope that time from cell towers or NTP fixes it shortly.
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}

//
// Default the timezone property to GMT if not set.
//
//设置时区,如果没有默认GMT
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
//设置默认语言
// If the system has "persist.sys.language" and friends set, replace them with
// "persist.sys.locale". Note that the default locale at this point is calculated
// using the "-Duser.locale" command line flag. That flag is usually populated by
// AndroidRuntime using the same set of system properties, but only the system_server
// and system apps are allowed to set them.
//
// NOTE: Most changes made here will need an equivalent change to
// core/jni/AndroidRuntime.cpp
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", "");
}
//配置systemserver
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
PackageItemInfo.setForceSafeLabels(true);

//SQLite配置
// Default to FULL within the system server.
SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;

// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
SQLiteCompatibilityWalFlags.init(null);

// Here we go!
Slog.i(TAG, "Entered the Android system server!");
int uptimeMillis = (int) SystemClock.elapsedRealtime();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
}

// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can | xq oqi't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
//变更虚拟机的库文件
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());

//清除vm内存增长上限,由于启动过程中需要更多的虚拟机内存空间
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();

//设置内存的可能有效使用率为0.8
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

//针对部分设备依赖于运行时就产生指纹信息,因此需要在开机完成前定义
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();

//访问环境变量前,需要明确指定用户
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);

//拒绝接受bundles
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
//开启trace for parcel
// Within the system server, when parceling exceptions, include the stack trace
Parcel.setStackTraceParceling(true);

//确保系统的binder调用,总运行在前台优先级
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
//增加system_server binder线程池的线程数为31,默认是16
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
//进程等级为前台优先级
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);

//主线程looper在当前线程运行
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

//加载android_servers.so库,该库源码在frameworks/base/services/目录下
// Initialize native services.
System.loadLibrary("android_servers");

//检查上次关机过程是否失败
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();

//初始化系统上下文
// Initialize the system context.
createSystemContext();

//创建系统服务管理
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects中
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

//开启systemserver初始化任务的线程池
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}

// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices(); //引导服务
startCoreServices(); //核心服务
startOtherServices(); //其他服务
//关闭systemserver初始化任务的线程池
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}

StrictMode.initVmDefaults(null);

if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
int uptimeMillis = (int) SystemClock.elapsedRealtime();
MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
final int MAX_UPTIME_MILLIS = 60 * 1000;
if (uptimeMillis > MAX_UPTIME_MILLIS) {
Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
"SystemServer init took too long. uptimeMillis=" + uptimeMillis);
}
}

// Diagnostic to ensure that the system is in a base healthy state. Done here as a common
// non-zygote process.
if (!VMRuntime.hasBootImageSpaces()) {
Slog.wtf(TAG, "Runtime is not running with a boot image!");
}

//循环执行
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

1.3 performPendingShutdown

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
private void performPendingShutdown() {
final String shutdownAction = SystemProperties.get(
ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
//如果关机异常
if (shutdownAction != null && shutdownAction.length() > 0) {
boolean reboot = (shutdownAction.charAt(0) == '1');

final String reason;
if (shutdownAction.length() > 1) {
reason = shutdownAction.substring(1, shutdownAction.length());
} else {
reason = null;
}

// If it's a pending reboot into recovery to apply an update,
// always make sure uncrypt gets executed properly when needed.
// If '/cache/recovery/block.map' hasn't been created, stop the
// reboot which will fail for sure, and get a chance to capture a
// bugreport when that's still feasible. (Bug: 26444951)
// /cache/recovery/block.map不存在则直接返回
if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
File packageFile = new File(UNCRYPT_PACKAGE_FILE);
if (packageFile.exists()) {
String filename = null;
try {
filename = FileUtils.readTextFile(packageFile, 0, null);
} catch (IOException e) {
Slog.e(TAG, "Error reading uncrypt package file", e);
}

if (filename != null && filename.startsWith("/data")) {
if (!new File(BLOCK_MAP_FILE).exists()) {
Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
"unexpected runtime restart?");
return;
}
}
}
}
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
//重启
ShutdownThread.rebootOrShutdown(null, reboot, reason);
}
}
};

//通知ui
// ShutdownThread must run on a looper capable of displaying the UI.
Message msg = Message.obtain(UiThread.getHandler(), runnable);
msg.setAsynchronous(true);
UiThread.getHandler().sendMessage(msg);

}
}

1.4 createSystemContext

1
2
3
4
5
6
7
8
9
private void createSystemContext() {
//创建systemserver进程的上下文信息
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//设置主题
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

1.5 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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/**
* Starts the small tangle of critical services that are needed to get
* the system off the ground. These services have complex mutual dependencies
* which is why we initialize them all in one place here. Unless your service
* is also entwined in these dependencies, it should be initialized in one of
* the other functions.
*/
private void startBootstrapServices() {
//读取systemconfig
Slog.i(TAG, "Reading configuration...");
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
traceBeginAndSlog(TAG_SYSTEM_CONFIG);
SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
traceEnd();

//启动installd服务
// Wait for installd to finish starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions. We need this to complete before we initialize other services.
traceBeginAndSlog("StartInstaller");
Installer installer = mSystemServiceManager.startService(Installer.class);
traceEnd();

//启动DeviceIdentifiersPolicyService服务
// In some cases after launching an app we need to access device identifiers,
// therefore register the device identifier policy before the activity manager.
traceBeginAndSlog("DeviceIdentifiersPolicyService");
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
traceEnd();

//启动 ActivityManagerService服务
// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();

//启动 PowerManagerService服务
// Power manager needs to be started early because other services need it.
// Native daemons may be watching for it to be registered so it must be ready
// to handle incoming binder calls immediately (including being able to verify
// the permissions for those calls).
traceBeginAndSlog("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();

//初始化PowerManagement
// Now that the power manager has been started, let the activity manager
// initialize power management features.
traceBeginAndSlog("InitPowerManagement");
mActivityManagerService.initPowerManagement();
traceEnd();

//启动 RecoverySystemService服务
// Bring up recovery system in case a rescue party needs a reboot
traceBeginAndSlog("StartRecoverySystemService");
mSystemServiceManager.startService(RecoverySystemService.class);
traceEnd();

//通知正在启动
// Now that we have the bare essentials of the OS up and running, take
// note that we just booted, which might send out a rescue party if
// we're stuck in a runtime restart loop.
RescueParty.noteBoot(mSystemContext);

//启动 LightsService服务
// Manages LEDs and display backlight so we need it to bring up the display.
traceBeginAndSlog("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
traceEnd();

//启动 SidekickService服务
traceBeginAndSlog("StartSidekickService");
// Package manager isn't started yet; need to use SysProp not hardware feature
if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
}
traceEnd();

//启动 DisplayManagerService服务
// Display manager is needed to provide display metrics before package manager
// starts up.
traceBeginAndSlog("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
traceEnd();

//Phase100:初始化package manager之前,需要默认的显示
// We need the default display before we can initialize the package manager.
traceBeginAndSlog("WaitForDisplay");
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
traceEnd();

//加密状态下只运行核心应用
// Only run "core" apps if we're encrypting the device.
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;
}

// Start the package manager.
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_package_manager_init_start",
(int) SystemClock.elapsedRealtime());
}

//启动PackageManagerService
traceBeginAndSlog("StartPackageManagerService");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
traceEnd();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
MetricsLogger.histogram(null, "boot_package_manager_init_ready",
(int) SystemClock.elapsedRealtime());
}
//管理A/B OTA dexopt
//A/B 是系统有两个分区,一个是新版本一个是旧版本,主要用于升级
// Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
// A/B artifacts after boot, before anything else might touch/need them.
// Note: this isn't needed during decryption (we don't have /data anyways).
if (!mOnlyCore) {
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
false);
if (!disableOtaDexopt) {
traceBeginAndSlog("StartOtaDexOptService");
try {
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
traceEnd();
}
}
}

//启动UserManagerService
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
traceEnd();

// Initialize attribute cache used to cache resources from packages.
traceBeginAndSlog("InitAttributerCache");
AttributeCache.init(mSystemContext);
traceEnd();

// 通过AMS设置系统集成Application
// Set up the Application instance for the system process and get started.
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();

// DisplayManagerService needs to setup android.display scheduling related policies
// since setSystemProcess() would have overridden policies due to setProcessGroup
mDisplayManagerService.setupSchedulerPolicies();

//启动OverlayManagerService
// Manages Overlay packages
traceBeginAndSlog("StartOverlayManagerService");
OverlayManagerService overlayManagerService = new OverlayManagerService(
mSystemContext, installer);
mSystemServiceManager.startService(overlayManagerService);
traceEnd();

if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
// DisplayManager needs the overlay immediately.
overlayManagerService.updateSystemUiContext();
LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
}

//线程池启动SensorService
// The sensor service needs access to package manager service, app ops
// service, and permissions service, therefore we start it after them.
// Start sensor service in a separate thread. Completion should be checked
// before using it.
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);
}

1.6 startCoreServices

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
/**
* Starts some essential services that are not tangled up in the bootstrap process.
*/
private void startCoreServices() {

//启动BatteryService服务
traceBeginAndSlog("StartBatteryService");
// Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class);
traceEnd();

//启动UsageStatsService服务
// Tracks application usage stats.
traceBeginAndSlog("StartUsageService");
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
traceEnd();

//启动WebViewUpdateService服务
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
traceBeginAndSlog("StartWebViewUpdateService");
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
traceEnd();
}

//记录binder calls时间
// Tracks cpu time spent in binder calls
traceBeginAndSlog("StartBinderCallsStatsService");
BinderCallsStatsService.start();
traceEnd();

//启动BugreportManagerService服务
// Service to capture bugreports.
traceBeginAndSlog("StartBugreportManagerService");
mSystemServiceManager.startService(BugreportManagerService.class);
traceEnd();

//启动GpuService服务
// Serivce for GPU and GPU driver.
traceBeginAndSlog("GpuService");
mSystemServiceManager.startService(GpuService.class);
traceEnd();
}

1.7 startOtherServices

该方法较长,有一千多行,逻辑很简单,主要是启动一系列的服务分类,后面将会对服务进行一个简单分类。

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
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored
* and organized.
*/
private void startOtherServices() {
...
//resolver
mContentResolver = context.getContentResolver();
...
//provider
mActivityManagerService.installSystemProviders();
...
//alarm
mSystemServiceManager.startService(AlarmManagerService.class);
//Watchdog
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
//inputManager
inputManager = new InputManagerService(context);
//wms
wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore, new PhoneWindowManager());
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
mActivityManagerService.setWindowManager(wm);
wm.onInitReady();
//Bluetooth
mSystemServiceManager.startService(BluetoothService.class);
//见packagemanagerservice启动
mPackageManagerService.updatePackagesIfNeeded();
mPackageManagerService.performFstrimIfNeeded();
//statu
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
location = new LocationManagerService(context);
//dream
// Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
mSystemServiceManager.startService(DreamManagerService.class);
...
// It is now time to start up the app processes..
vibrator.systemReady();
lockSettings.systemReady();

//phase480和phase500
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

//准备好window、packagemanager、display服务
wm.systemReady();
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(safeMode, mOnlyCore);
...
//phase 520
mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
mActivityManagerService.systemReady(() -> {
//phase 550
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
...
//phase 600
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
...
}, BOOT_TIMINGS_TRACE_LOG);
}

SystemServer启动各种服务的最后一个环节是AMS.systemReady,这里以后会对AMS启动流程详细介绍。

这样SystemServer的主线程的启动流程就结束了,进入loop状态,等待其他线程通过handler发送消息到主线程再处理。

二、服务启动阶段

整个SystemServer的启动过程中,mSystemServiceManager.startBootPhase一直在其中:

systemserver进程创建准备完成
0-100
创建DPS、AMS、PMS、RSS、LS、SS、DMS服务
100-480
创建PKMS、UMS、OMS、BS、BMS等服务
480-500无任何操作
500-520
WMS、PMS、PKMS、DMS依次调用systemReady方法
520-550
定制的特殊服务
550-600
启动SystemUi,剩下服务调用systemReady,启动watchDog
600-1000
各种服务调用systemRunning方法,AMS调用finishBooting

其中PHASE_BOOT_COMPLETED=1000,该阶段是Boot和home应用启动完成。系统服务更倾向监听该阶段,而不是注册广播ACTION_BOOT_COMPLETED,从而降低系统延迟。

各个阶段在源码的位置大概如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public final class SystemServer{
private void startBootstrapServices() {
//phase100
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
}
private void startOtherServices() {
//phase480
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
//phase500
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
//phase 520
mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
mActivityManagerService.systemReady(() -> {
//phase 550
mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
...
//phase 600
mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
...
}, BOOT_TIMINGS_TRACE_LOG);
}
}
1
2
3
4
5
6
7
8
public class ActivityManagerService
final void finishBooting() {
...
//phase 1000
mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
...
}
}

下面将介绍下每个阶段完成的工作:

2.1 Phase 0

创建下面引导服务
DeviceIdentifiersPolicyService
ActivityManagerService
PowerManagerService
RecoverySystemService
LightsService
SidekickService
DisplayManagerService

2.2 Phase 100

进入阶段PHASE_WAIT_FOR_DEFAULT_DISPLAY=100回调服务
onBootPhase(100)
DisplayManagerService监听调用
然后创建下面服务
PackageManagerService
UserManagerService
OverlayManagerService
BatteryService
UsageStatsService
WebViewUpdateService
BinderCallsStatsService
BugreportManagerService
GpuService

2.3 Phase 480

进入PHASE_LOCK_SETTINGS_READY=480回调服务

onBootPhase(480)
DevicePolicyManagerService监听调用
进入阶段480后立马进入到500

2.4 Phase 500

进入PHASE_SYSTEM_SERVICES_READY=500
进入到这个阶段,服务能安全的调用核心系统服务
各大服务执行systemReady

wm.systemReady();
mPowerManagerService.systemReady()
mPackageManagerService.systemReady()
mDisplayManagerService.systemReady()

DeviceSpecificServices

2.5 Phase 520

进入到PHASE_DEVICE_SPECIFIC_SERVICES_READY=520

onBootPhase(520)

DeviceSpecificServices监听调用,为厂商定制的一些特殊服务

最后执行AMS.SystemReady

2.6 Phase 550

进入到PHASE_ACTIVITY_MANAGER_READY=550

onBootPhase(550)

此时 AMS.mSystemReady = true,已经准备就绪,该阶段服务能广播Intent,但是systemserver主线程并没有就绪.

主要是个服务执行systemReady,还有AMS启动Native crash监控,加载webview,启动SystemUi等

mActivityManagerService.startObservingNativeCrashes();
mWebViewUpdateService.prepareWebViewInSystemServer();
CarServiceHelperService
startSystemUi(context, windowManagerF)
networkManagementF.systemReady()
networkPolicyF.networkScoreAndNetworkManagementServiceReady()
ipSecServiceF.systemReady()
networkStatsF.systemReady()
connectivityF.systemReady()
networkPolicyF.systemReady()
Watchdog.getInstance().start();
mPackageManagerService.waitForAppDataPrepared()

2.7 Phase 600

进入到PHASE_THIRD_PARTY_APPS_CAN_START=600

onBootPhase(600)

主要是各种服务的systemRunning

NetworkStackClient.getInstance().start(context);
locationF.systemRunning()
countryDetectorF.systemRunning()
networkTimeUpdaterF.systemRunning()
inputManagerF.systemRunning()
telephonyRegistryF.systemRunning()
mediaRouterF.systemRunning()
mmsServiceF.systemRunning()
incident.systemRunning()

2.8 Phase 1000

经过一序列的流程,最后执行AMS.finishBooting,则进入到PHASE_BOOT_COMPLETED=1000

onBootPhase(1000)

到此,系统服务启动完成,systemsever进程启动完成进入到Loop().loop状态,等待消息队列MessageQueue中的消息到来,则马上进入执行状态。

三、服务类别

systemsever进程,从源码的角度分为引导服务,核心服务,其他服务3类,主要如下:

1.引导服务(11个)

DeviceIdentifiersPolicyService
ActivityManagerService
PowerManagerService
RecoverySystemService
LightsService
SidekickService
DisplayManagerService
PackageManagerService
UserManagerService
OverlayManagerService
SensorService

2.核心服务(6个)

BatteryService
UsageStatsService
WebViewUpdateService
BinderCallsStatsService
BugreportManagerService
GpuService

3.其他服务(100个+)

KeyAttestationApplicationIdProviderService KeyChainSystemService SchedulingPolicyService
TelecomLoaderService AccountManagerService ContentService
DropBoxManagerService VibratorService DynamicAndroidService
ConsumerIrService AlarmManagerService InputManagerService
WindowManagerService VrManagerService BluetoothService
IpConnectivityMetrics NetworkWatchlistService PinnerService
InputMethodManagerService AccessibilityManagerService StartStorageManagerService
StorageStatsService UiModeManagerService LockSettingsService
PersistentDataBlockService OemLockService DeviceIdleController
DevicePolicyManagerService StatusBarManagerService ClipboardService
NetworkManagementService StartIpSecService TextServicesManagerService
TextClassificationManagerService NetworkScoreService NetworkStatsService
NetworkPolicyManagerService WifiService WifiScanningService
RttService WifiAwareService WifiP2pService
LowpanService EthernetService ConnectivityService
NsdService SystemUpdateManagerService UpdateLockService
NotificationManagerService DeviceStorageMonitorService LocationManagerService
CountryDetectorService TimeDetectorService SearchManagerService
WallpaperManagerService AudioService BroadcastRadioService
MidiService UsbService SerialService
HardwarePropertiesManagerService TwilightService ColorDisplayService
JobSchedulerService SoundTriggerService TrustManagerService
BackupManagerService AppWidgerService VoiceInteractionManagerService
GestureLauncherService SensorNotificationService ContextHubSystemService
ContextHubSystemService DiskStatsService TimeZoneRulesManagerService
NetworkTimeUpdateService EmergencyAffordanceService DreamManagerService
GraphicsStatsService CoverageService PrintManagerService
CompanionDeviceManagerService RestrictionsManagerService MediaSessionService
MediaUpdateService HdmiControlService TvInputManagerService
MediaResourceMonitorService TvRemoteService MediaRouterService
FingerprintService BackgroundDexOptService PruneInstantAppsJobService
ShortcutService LauncherAppsService CrossProfileAppsService
MediaProjectionManagerService WearConfigService WearConnectivityService
WearTimeService WearLeftyService WearGlobalActionsService
SliceManagerService CameraServiceProxy IoTSystemService
StatsCompanionService MmsServiceBroker AutofillManagerService
DeviceSpecificServices

以后的文章将介绍一些常用的Service。

下面是华为荣耀9(Android9.0),SystemServer的开机日志:

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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
--------- beginning of main
--------- beginning of system
07-29 14:46:25.853 1296 1296 I SystemServer: InitBeforeStartServices
07-29 14:46:25.857 1296 1296 I SystemServer: Entered the Android system server!
07-29 14:46:26.175 1296 1296 I SystemServer: StartServices
07-29 14:46:26.175 1296 1296 I SystemServer: Reading configuration...
07-29 14:46:26.175 1296 1296 I SystemServer: ReadingSystemConfig
07-29 14:46:26.175 1296 1296 I SystemServer: StartInstaller
07-29 14:46:26.180 1296 1296 I SystemServer: DeviceIdentifiersPolicyService
07-29 14:46:26.184 1296 1296 I SystemServer: StartActivityManager
07-29 14:46:26.682 1296 1296 I SystemServer: StartPowerManager
07-29 14:46:26.746 1296 1296 I SystemServer: PG Manager service
07-29 14:46:26.748 1296 1296 I SystemServer: InitPowerManagement
07-29 14:46:26.750 1296 1296 I SystemServer: StartRecoverySystemService
07-29 14:46:26.755 1296 1296 I SystemServer: StartLightsService
07-29 14:46:26.766 1296 1296 I SystemServer: StartSidekickService
07-29 14:46:26.766 1296 1296 I SystemServer: StartDisplayManager
07-29 14:46:26.800 1296 1296 I SystemServer: HwSecurityService start success
07-29 14:46:26.800 1296 1296 I SystemServer: WaitForDisplay
07-29 14:46:26.804 1296 1296 I SystemServer: StartPackageManagerService
07-29 14:46:26.804 1296 1296 I SystemServer: Package Manager
07-29 14:46:29.388 1296 1296 I SystemServer: Finish_StartPackageManagerService
07-29 14:46:29.389 1296 1296 I SystemServer: StartOtaDexOptService
07-29 14:46:29.390 1296 1296 I SystemServer: StartUserManagerService
07-29 14:46:29.390 1296 1296 I SystemServer: InitAttributerCache
07-29 14:46:29.390 1296 1296 I SystemServer: SetSystemProcess
07-29 14:46:29.398 1296 1296 I SystemServer: StartOverlayManagerService
07-29 14:46:29.399 1296 1296 I SystemServer: StartBatteryService
07-29 14:46:29.467 1296 1296 I SystemServer: StartUsageService
07-29 14:46:29.501 1296 1296 I SystemServer: StartWebViewUpdateService
07-29 14:46:29.504 1296 1296 I SystemServer: StartBinderCallsStatsService
07-29 14:46:29.506 1296 1309 I SystemServer: SecondaryZygotePreload
07-29 14:46:29.506 1296 1296 I SystemServer: StartKeyAttestationApplicationIdProviderService
07-29 14:46:29.507 1296 1296 I SystemServer: StartKeyChainSystemService
07-29 14:46:29.508 1296 1296 I SystemServer: StartSchedulingPolicyService
07-29 14:46:29.509 1296 1296 I SystemServer: StartTelecomLoaderService
07-29 14:46:29.509 1296 1296 I SystemServer: StartTelephonyRegistry
07-29 14:46:29.509 1296 1296 I SystemServer: Telephony Registry
07-29 14:46:29.511 1296 1296 I SystemServer: StartEntropyMixer
07-29 14:46:29.709 1296 1296 I SystemServer: StartAccountManagerService
07-29 14:46:29.713 1296 1296 I SystemServer: StartContentService
07-29 14:46:29.717 1296 1296 I SystemServer: InstallSystemProviders
07-29 14:46:29.779 1296 1296 I SystemServer: StartDropBoxManager
07-29 14:46:29.780 1296 1296 I SystemServer: StartVibratorService
07-29 14:46:29.784 1296 1296 I SystemServer: StartConsumerIrService
07-29 14:46:29.784 1296 1296 I SystemServer: StartAlarmManagerService
07-29 14:46:29.795 1296 1296 I SystemServer: Init Watchdog
07-29 14:46:29.796 1296 1296 I SystemServer: StartInputManagerService
07-29 14:46:29.796 1296 1296 I SystemServer: Input Manager
07-29 14:46:29.827 1296 1296 I SystemServer: StartHwSysResManagerService
07-29 14:46:29.899 1296 1296 I SystemServer: StartWindowManagerService
07-29 14:46:29.996 1296 1296 I SystemServer: SetWindowManagerService
07-29 14:46:30.016 1296 1296 I SystemServer: WindowManagerServiceOnInitReady
07-29 14:46:30.046 1296 1296 I SystemServer: StartVrManagerService
07-29 14:46:30.049 1296 1296 I SystemServer: StartInputManager
07-29 14:46:30.054 1296 1296 I SystemServer: DisplayManagerWindowManagerAndInputReady
07-29 14:46:30.054 1296 1296 I SystemServer: StartBluetoothService
07-29 14:46:30.062 1296 1296 I SystemServer: IpConnectivityMetrics
07-29 14:46:30.066 1296 1296 I SystemServer: NetworkWatchlistService
07-29 14:46:30.074 1296 1296 I SystemServer: PinnerService
07-29 14:46:30.075 1296 1296 I SystemServer: ZrHungService
07-29 14:46:30.077 1296 1296 I SystemServer: StartInputMethodManagerLifecycle
07-29 14:46:30.077 1296 1296 I SystemServer: Input Method Service
07-29 14:46:30.091 1296 1296 I SystemServer: Secure Input Method Service
07-29 14:46:30.103 1296 1296 I SystemServer: StartAccessibilityManagerService
07-29 14:46:30.105 1296 1296 I SystemServer: MakeDisplayReady
07-29 14:46:30.125 1296 1296 I SystemServer: StartStorageManagerService
07-29 14:46:30.156 1296 1296 I SystemServer: StartStorageStatsService
07-29 14:46:30.158 1296 1296 I SystemServer: StartUiModeManager
07-29 14:46:30.159 1296 1296 I SystemServer: UpdatePackagesIfNeeded
07-29 14:46:30.159 1296 1296 I SystemServer: PerformFstrimIfNeeded
07-29 14:46:30.164 1296 1296 I SystemServer: StartLockSettingsService
07-29 14:46:30.191 1296 1296 I SystemServer: StartDeviceIdleController
07-29 14:46:30.202 1296 1296 I SystemServer: StartDevicePolicyManager
07-29 14:46:30.257 1296 1296 I SystemServer: StartStatusBarManagerService
07-29 14:46:30.257 1296 1296 I SystemServer: Status Bar
07-29 14:46:30.259 1296 1296 I SystemServer: StartClipboardService
07-29 14:46:30.263 1296 1296 I SystemServer: StartNetworkManagementService
07-29 14:46:30.274 1296 1296 I SystemServer: StartIpSecService
07-29 14:46:30.276 1296 1296 I SystemServer: StartTextServicesManager
07-29 14:46:30.277 1296 1296 I SystemServer: StartTextClassificationManagerService
07-29 14:46:30.277 1296 1296 I SystemServer: StartNetworkScoreService
07-29 14:46:30.279 1296 1296 I SystemServer: StartNetworkStatsService
07-29 14:46:30.284 1296 1296 I SystemServer: StartNetworkPolicyManagerService
07-29 14:46:30.289 1296 1296 I SystemServer: StartWifi
07-29 14:46:30.789 1296 1296 I SystemServer: StartWifiScanning
07-29 14:46:30.790 1296 1296 I SystemServer: StartWifiP2P
07-29 14:46:30.806 1296 1296 I SystemServer: StartEthernet
07-29 14:46:30.807 1296 1296 I SystemServer: StartConnectivityService
07-29 14:46:30.865 1296 1296 I SystemServer: StartNsdService
07-29 14:46:30.867 1296 1296 I SystemServer: StartSystemUpdateManagerService
07-29 14:46:30.868 1296 1296 I SystemServer: StartUpdateLockService
07-29 14:46:30.869 1296 1296 I SystemServer: StartNotificationManager
07-29 14:46:31.017 1296 1296 I SystemServer: StartDeviceMonitor
07-29 14:46:31.020 1296 1296 I SystemServer: TUI Connect enable true
07-29 14:46:31.022 1296 1296 I SystemServer: VR Display enable true
07-29 14:46:31.023 1296 1296 I SystemServer: StartLocationManagerService
07-29 14:46:31.023 1296 1296 I SystemServer: Location Manager
07-29 14:46:31.041 1296 1296 I SystemServer: StartCountryDetectorService
07-29 14:46:31.042 1296 1296 I SystemServer: StartSearchManagerService
07-29 14:46:31.043 1296 1296 I SystemServer: StartWallpaperManagerService
07-29 14:46:31.048 1296 1296 I SystemServer: StartTrustManager
07-29 14:46:31.049 1296 1296 I SystemServer: StartAudioService
07-29 14:46:31.133 1296 1296 I SystemServer: StartDockObserver
07-29 14:46:31.134 1296 1296 I SystemServer: StartWiredAccessoryManager
07-29 14:46:31.134 1296 1296 I SystemServer: StartMidiManager
07-29 14:46:31.135 1296 1296 I SystemServer: StartUsbService
07-29 14:46:31.154 1296 1296 I SystemServer: StartSerialService
07-29 14:46:31.155 1296 1296 I SystemServer: StartHardwarePropertiesManagerService
07-29 14:46:31.156 1296 1296 I SystemServer: StartTwilightService
07-29 14:46:31.166 1296 1296 I SystemServer: StartSoundTrigger
07-29 14:46:31.167 1296 1296 I SystemServer: StartBackupManager
07-29 14:46:31.167 1296 1296 I SystemServer: StartAppWidgerService
07-29 14:46:31.172 1296 1296 I SystemServer: StartVoiceRecognitionManager
07-29 14:46:31.173 1296 1296 I SystemServer: StartSensorNotification
07-29 14:46:31.173 1296 1296 I SystemServer: StartContextHubSystemService
07-29 14:46:31.224 1296 1296 I SystemServer: StartDiskStatsService
07-29 14:46:31.226 1296 1296 I SystemServer: attestation Service
07-29 14:46:31.234 1296 1296 I SystemServer: StartNetworkTimeUpdateService
07-29 14:46:31.235 1296 1296 I SystemServer: StartCommonTimeManagementService
07-29 14:46:31.236 1296 1296 I SystemServer: CertBlacklister
07-29 14:46:31.237 1296 1296 I SystemServer: StartEmergencyAffordanceService
07-29 14:46:31.237 1296 1296 I SystemServer: StartDreamManager
07-29 14:46:31.237 1296 1296 I SystemServer: AddGraphicsStatsService
07-29 14:46:31.239 1296 1296 I SystemServer: StartPrintManager
07-29 14:46:31.241 1296 1296 I SystemServer: StartCompanionDeviceManager
07-29 14:46:31.242 1296 1296 I SystemServer: StartRestrictionManager
07-29 14:46:31.243 1296 1296 I SystemServer: StartMediaSessionService
07-29 14:46:31.245 1296 1296 I SystemServer: StartMediaUpdateService
07-29 14:46:31.245 1296 1296 I SystemServer: StartMediaResourceMonitor
07-29 14:46:31.246 1296 1296 I SystemServer: StartMediaRouterService
07-29 14:46:31.247 1296 1296 I SystemServer: StartFingerprintSensor
07-29 14:46:31.254 1296 1296 I SystemServer: serviceClass doesn't null
07-29 14:46:31.254 1296 1296 I SystemServer: start HwFingerPrintService
07-29 14:46:31.258 1296 1296 I SystemServer: FingerPrintService ready
07-29 14:46:31.258 1296 1296 I SystemServer: StartBackgroundDexOptService
07-29 14:46:31.259 1296 1296 I SystemServer: StartPruneInstantAppsJobService
07-29 14:46:31.259 1296 1296 I SystemServer: StartShortcutServiceLifecycle
07-29 14:46:31.260 1296 1296 I SystemServer: StartLauncherAppsService
07-29 14:46:31.261 1296 1296 I SystemServer: StartCrossProfileAppsService
07-29 14:46:31.262 1296 1296 I SystemServer: StartMediaProjectionManager
07-29 14:46:31.264 1296 1296 I SystemServer: StartSliceManagerService
07-29 14:46:31.266 1296 1296 I SystemServer: StartCameraServiceProxy
07-29 14:46:31.268 1296 1296 I SystemServer: StartStatsCompanionService
07-29 14:46:31.326 1296 1296 I SystemServer: StartJitCompilation
07-29 14:46:31.326 1296 1296 I SystemServer: StartMmsService
07-29 14:46:31.326 1296 1296 I SystemServer: StartAutoFillService
07-29 14:46:31.334 1296 1296 I SystemServer: MakeVibratorServiceReady
07-29 14:46:31.335 1296 1296 I SystemServer: MakeLockSettingsServiceReady
07-29 14:46:31.358 1296 1296 I SystemServer: StartBootPhaseLockSettingsReady
07-29 14:46:31.364 1296 1296 I SystemServer: StartBootPhaseSystemServicesReady
07-29 14:46:31.767 1296 1296 I SystemServer: MakeWindowManagerServiceReady
07-29 14:46:31.799 1296 1296 I SystemServer: MakePowerManagerServiceReady
07-29 14:46:31.876 1296 1296 I SystemServer: MakePackageManagerServiceReady
07-29 14:46:32.002 1296 1296 I SystemServer: MakeDisplayManagerServiceReady
07-29 14:46:32.003 1296 1296 I SystemServer: StartDeviceSpecificServices
07-29 14:46:32.003 1296 1296 I SystemServer: StartBootPhaseDeviceSpecificServicesReady
07-29 14:46:32.064 1296 1296 I SystemServer: Making services ready
07-29 14:46:32.064 1296 1296 I SystemServer: StartActivityManagerReadyPhase
07-29 14:46:33.190 1296 1296 I SystemServer: StartObservingNativeCrashes
07-29 14:46:33.190 1296 1296 I SystemServer: StartSystemUI
07-29 14:46:33.191 1296 1309 I SystemServer: WebViewFactoryPreparation
07-29 14:46:34.615 1296 1296 I SystemServer: MakeNetworkManagementServiceReady
07-29 14:46:34.812 1296 1296 I SystemServer: MakeIpSecServiceReady
07-29 14:46:34.812 1296 1296 I SystemServer: MakeNetworkStatsServiceReady
07-29 14:46:34.924 1296 1296 I SystemServer: MakeConnectivityServiceReady
07-29 14:46:34.954 1296 1296 I SystemServer: MakeNetworkPolicyServiceReady
07-29 14:46:35.081 1296 1296 I SystemServer: StartWatchdog
07-29 14:46:35.081 1296 1296 I SystemServer: PhaseThirdPartyAppsCanStart
07-29 14:46:35.225 1296 1296 I SystemServer: MakeLocationServiceReady
07-29 14:46:35.233 1296 1296 I SystemServer: MakeCountryDetectionServiceReady
07-29 14:46:35.233 1296 1296 I SystemServer: MakeNetworkTimeUpdateReady
07-29 14:46:35.234 1296 1296 I SystemServer: MakeCommonTimeManagementServiceReady
07-29 14:46:35.234 1296 1296 I SystemServer: MakeInputManagerServiceReady
07-29 14:46:35.306 1296 1296 I SystemServer: MakeTelephonyRegistryReady
07-29 14:46:35.306 1296 1296 I SystemServer: MakeMediaRouterServiceReady
07-29 14:46:35.306 1296 1296 I SystemServer: MakeMmsServiceReady
07-29 14:46:35.306 1296 1296 I SystemServer: IncidentDaemonReady
07-29 14:46:35.411 1296 1296 I SystemServer: Finish_StartServices