SystemServer 的启动流程

在Android中,包括AMS、PMS、WMS在内几乎所有核心服务都会运行在SystemServer进程里。它是由Zygote fork生成的(前面我们已经分析过Zygote的启动),下面我们一起来分析下SystemServer的启动过程。

1. Zygote启动SystemServer

1.1 ZygoteInit的handleSystemServerProcess方法

在前文中我们提到过Zygote会调用forkSystemServer方法来fork SystemServer。fork完后需要调用handleSystemServerProcess来完成剩下的工作。

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
//frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
// 设置新目录和文件权限为0077,即所有者权限
Os.umask(S_IRWXG | S_IRWXO);
if (parsedArgs.niceName != null) {
// 设置进程名为"system_server"
Process.setArgV0(parsedArgs.niceName);
}
// 从init.environ.rc中获取环境变量
// /system/framework/目录下的services.jar、ethernet-service.jar、wifi-service.jar、和com.android.location.provider.jar
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
// 对环境变量中jar包进行dex优化
performSystemServerDexOpt(systemServerClasspath);
// 仅限debug/eng软件捕获profiles
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
try {
prepareSystemServerProfile(systemServerClasspath);
} catch (Exception e) {
Log.wtf(TAG, "Failed to set up system server profile", e);
}
}
}
if (parsedArgs.invokeWith != null) {
String[] args = parsedArgs.remainingArgs;
// 执行新进程时ART需要有正确的system server class路径
if (systemServerClasspath != null) {
String[] amendedArgs = new String[args.length + 2];
amendedArgs[0] = "-cp";
amendedArgs[1] = systemServerClasspath;
System.arraycopy(args, 0, amendedArgs, 2, args.length);
args = amendedArgs;
}
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
// 将相关参数传给SystemServer
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}

1.2 ZygoteInit的performSystemServerDexOpt方法

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
// 如果需要,对classPath的元素执行dex-opt。选择当前运行时的指令集。若编译了某些内容则返回true。
private static boolean performSystemServerDexOpt(String classPath) {
final String[] classPathElements = classPath.split(":");
final IInstalld installd = IInstalld.Stub
.asInterface(ServiceManager.getService("installd"));
final String instructionSet = VMRuntime.getRuntime().vmInstructionSet();
String classPathForElement = "";
boolean compiledSomething = false;
for (String classPathElement : classPathElements) {
// 系统服务器完全AOT,从未为配置文件引导编译进行概要分析。
String systemServerFilter = SystemProperties.get(
"dalvik.vm.systemservercompilerfilter", "speed");
int dexoptNeeded;
try {
dexoptNeeded = DexFile.getDexOptNeeded(
classPathElement, instructionSet, systemServerFilter,
null /* classLoaderContext */, false /* newProfile */,
false /* downgrade */);
} catch (FileNotFoundException ignored) {
// 无需加入classpath。
Log.w(TAG, "Missing classpath element for system server: " + classPathElement);
continue;
} catch (IOException e) {
// 用于防止出现IO异常的保守设计。
Log.w(TAG, "Error checking classpath element for system server: "
+ classPathElement, e);
dexoptNeeded = DexFile.NO_DEXOPT_NEEDED;
}
if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
final String packageName = "*";
final String outputPath = null;
final int dexFlags = 0;
final String compilerFilter = systemServerFilter;
final String uuid = StorageManager.UUID_PRIVATE_INTERNAL;
final String seInfo = null;
final String classLoaderContext =
getSystemServerClassLoaderContext(classPathForElement);
final int targetSdkVersion = 0; // SystemServer复用系统sdk版本
try {
// system权限执行dex优化
installd.dexopt(classPathElement, Process.SYSTEM_UID, packageName,
instructionSet, dexoptNeeded, outputPath, dexFlags, compilerFilter,
uuid, classLoaderContext, seInfo, false /* downgrade */,
targetSdkVersion, /*profileName*/ null, /*dexMetadataPath*/ null,
"server-dexopt");
compiledSomething = true;
} catch (RemoteException | ServiceSpecificException e) {
Log.w(TAG, "Failed compiling classpath element for system server: "
+ classPathElement, e);
}
}
classPathForElement = encodeSystemServerClassPath(
classPathForElement, classPathElement);
}
return compiledSomething;
}

1.3 ZygoteInit的zygoteInit方法

1
2
3
4
5
6
7
8
9
10
11
12
13
//frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
// 通过zygote进程启动时调用的主函数
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
// 重定向日志流
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit();
ZygoteInit.nativeZygoteInit();
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}

1.4 RuntimeInit的commonInit方法

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
//frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static final void commonInit() {
if (DEBUG) Slog.d(TAG, "Entered RuntimeInit!");
// 设置handler,适用于vm中所有线程。
// 应用可以替换默认handler,但是不能替换预处理的handler
LoggingHandler loggingHandler = new LoggingHandler();
RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
// 设置默认的未捕获异常处理的方法
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
// 安装使用Android持久时区系统属性的时区supplier。
RuntimeHooks.setTimeZoneIdSupplier(() -> SystemProperties.get("persist.sys.timezone"));
// 将java.util.logging的处理程序设置为使用Android日志工具。
// 奇怪的“new instance-and-then-throw-away”是“java.util.logging.config.class”系统属性工作的镜像。
// 不能在这里使用系统属性,因为记录器已经初始化了。
LogManager.getLogManager().reset();
new AndroidConfig();
// 使用的默认HTTP User-Agent来设置HttpURLConnection。
String userAgent = getDefaultUserAgent();
System.setProperty("http.agent", userAgent);
// 设置socket的tagger用于统计流量。
NetworkManagementSocketTagger.install();
// 如果在使用“-trace”启动的模拟器中运行,将VM置于仿真器跟踪分析模式,以便用户可以随时按F9/F10来捕获traces。当然,这会性能产生一定的影响。
String trace = SystemProperties.get("ro.kernel.android.tracing");
if (trace.equals("1")) {
Slog.i(TAG, "NOTE: emulator trace profiling enabled");
Debug.enableEmulatorTraceOutput();
}
initialized = true;
}

1.5 AndroidRuntime的nativeZygoteInit函数

1
2
3
4
5
6
//frameworks/base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
// gCurRuntime对应AppRuntime
gCurRuntime->nativeZygoteInit();
}
1
2
3
4
5
6
7
8
9
//frameworks/base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
// 调用open()打开/dev/binder驱动设备,再利用mmap()映射内核的地址空间,将Binder驱动的fd赋值ProcessState对象中的变量mDriverFD,用于交互操作。
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
// 启动新的binder线程
proc->startThreadPool();
}

1.6 RuntimeInit的applicationInit方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
// 如果应用程序调用System.exit(),则立即终止进程而不运行任何关闭hooks。无法正常关闭Android应用程序。
// 除此之外,Android运行时关闭hooks关闭Binder驱动程序,这可能导致剩余的运行线程在进程实际退出之前崩溃。
nativeSetExitWithoutCleanup(true);
// 避免持有大量不需要的内存,虚拟机的内存利用率参考值为0.75。
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
// 解析参数
final Arguments args = new Arguments(argv);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
// 剩余的参数传递给start类的静态main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}

1.7 RuntimeInit的findStaticMain方法

调用com.android.server.SystemServer的main方法。

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
//frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
// 通过抛出异常,回到ZygoteInit的main方法。
// 好处在于可以清空栈帧,提高栈帧利用率
return new MethodAndArgsCaller(m, argv);
}

2. SystemServer的启动

2.1 SystemServer的main方法及无参构造方法

1
2
3
4
5
6
7
8
9
10
11
12
//frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
public SystemServer() {
// 检查工厂测试模式
mFactoryTestMode = FactoryTest.getMode();
// 启动完成后,运行时重启。
mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
mRuntimeStartUptime = SystemClock.uptimeMillis();
}

2.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
//frameworks/base/services/java/com/android/server/SystemServer.java
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
// 将时间初始化到1970之后
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
// 设置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 (!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", "");
}
Binder.setWarnOnBlocking(true);
PackageItemInfo.setForceSafeLabels(true);
SQLiteCompatibilityWalFlags.init(null);
// 开始进入Android system server
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);
}
// 设置虚拟机库文件路径
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// 清除vm内存增长上限,因为启动过程会耗费较多虚拟机内存
VMRuntime.getRuntime().clearGrowthLimit();
// 设置堆栈利用率(0.8),确保system server尽可能有足够的内存来保证其一直运行
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// 指纹相关属性
Build.ensureFingerprintProperty();
// 访问环境变量前,需指定用户
Environment.setUserRequired(true);
BaseBundle.setShouldDefuse(true);
Parcel.setStackTraceParceling(true);
// 确保系统binder以前台优先级调用
BinderInternal.disableBackgroundScheduling(true);
// 在system_server进程中增加大量binder线程
BinderInternal.setMaxThreads(sMaxBinderThreads);
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库
System.loadLibrary("android_servers");
// 检查上次关机是否失败
performPendingShutdown();
// 初始化系统上下文
createSystemContext();
// 创建系统服务管理器
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
SystemServerInitThreadPool.get();
} finally {
traceEnd();
}
// 启动服务
try {
traceBeginAndSlog("StartServices");
// 启动系统boot服务
startBootstrapServices();
// 启动系统核心服务
startCoreServices();
// 启动其它非必要及时启动的系统服务
startOtherServices();
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);
}
}
// 启动looper,循环处理消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

2.3 SystemServer的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
//frameworks/base/services/java/com/android/server/SystemServer.java
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;
}
// 如果正在等待重启进入recovery模式OTA升级,需确保在需要时正确的执行解密。
// 若'/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) {
// 当"sys.shutdown.requested"值不为空会重启或者关机。
ShutdownThread.rebootOrShutdown(null, reboot, reason);
}
}
};
// ShutdownThread必须在能显示UI的looper上运行。
Message msg = Message.obtain(UiThread.getHandler(), runnable);
msg.setAsynchronous(true);
UiThread.getHandler().sendMessage(msg);
}
}

2.4 SystemServer的createSystemContext方法

该过程会创建对象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application等。

1
2
3
4
5
6
7
8
9
10
//frameworks/base/services/java/com/android/server/SystemServer.java
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
// 创建系统上下文并设置主题
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
// 创建系统界面上下文并设置主题
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

2.5 SystemServer的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
// 启动一些系统引导关键性的服务,这些服务具有复杂的相互依赖性。
private void startBootstrapServices() {
Slog.i(TAG, "Reading configuration...");
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
// 等待installd完成启动,这样它就有机会使用适当的权限创建关键目录,例如/data/user。因为初始化其它服务前我们需要完成这些工作。
Installer installer = mSystemServiceManager.startService(Installer.class);
// 在某些情况下启动应用之后需要访问设备标识符,因此在启动activity manager之前需要注册设备标识符策略。
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
// 启动ActivityManagerService。
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
// PowerManagerService需要尽可能早的启动,因为其它服务需要它。
// Native守护进程可能正在监听它是否已注册,因此它必须准备好立即处理传入的binder调用(包括能够验证这些调用的权限)。
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// 启动power manager之后,需要用ActivityManagerService来初始化power manager功能需求。
mActivityManagerService.initPowerManagement();
// 如果rescue party需要重启,则需要启动RecoverySystemService。
mSystemServiceManager.startService(RecoverySystemService.class);
// 现在已经启动并运行了操作系统的基本要素,如果我们遇到运行时反复重启,需要发送给rescue party。
RescueParty.noteBoot(mSystemContext);
// 启动管理LED并显示背光的LightService
mSystemServiceManager.startService(LightsService.class);
// Package manager还没有启动,需要使用SysProp而不是硬件功能。
if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
}
// 在Package manager启动之前,需要DisplayManagerService来提供display指标。
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// 在初始化Package manager之前需要默认的display。
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
// 如果设备是加密的,则只运行核心应用。
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。
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_package_manager_init_start",
(int) SystemClock.elapsedRealtime());
}
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
MetricsLogger.histogram(null, "boot_package_manager_init_ready",
(int) SystemClock.elapsedRealtime());
}
// 管理A/B OTA的dex优化工作的一个引导服务。解密过程中是不需要该服务的。
if (!mOnlyCore) {
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
false);
if (!disableOtaDexopt) {
try {
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
}
}
}
// 启动UserManagerService管理多用户。
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
// 初始化属性缓存,用于缓存包中的资源。
AttributeCache.init(mSystemContext);
// 为系统进程设置Application实例并开始使用。
mActivityManagerService.setSystemProcess();
// DisplayManagerService需要设置android.display调度相关策略,因为setSystemProcess()会因setProcessGroup而覆盖策略。
mDisplayManagerService.setupSchedulerPolicies();
// 启动StartOverlayManagerService管理Overlay的包。
OverlayManagerService overlayManagerService = new OverlayManagerService(
mSystemContext, installer);
mSystemServiceManager.startService(overlayManagerService);
if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
// DisplayManager需要马上overlay。
overlayManagerService.updateSystemUiContext();
LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
}
// SensorService需要访问PackageManagerService,PermissionService,所以最后启动它。
// SensorService是在线程中启动的,所以访问前需完成检查是否启动完成。
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
startSensorService();
}, START_SENSOR_SERVICE);
}

2.6 SystemServer的startCoreServices方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 启动引导阶段不互相依赖而又必须的服务。
private void startCoreServices() {
// 启动BatteryService统计电池电量。(需要LightService)
mSystemServiceManager.startService(BatteryService.class);
// 启动UsageStatService统计应用程序的使用。
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// 启动WebViewUpdateService跟踪可更新的WebView是否处于就绪状态并监视更新安装。
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
// 启动BinderCallsStatsService统计在binder调用中花费的cpu时间
BinderCallsStatsService.start();
// 启动BugreportManagerService抓取bug报告
mSystemServiceManager.startService(BugreportManagerService.class);
}

2.7 SystemServer的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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
// 启动一些没有被重构和管理的杂项服务。
private void startOtherServices() {
...
try {
final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
// 我们在webview工厂准备之前~1s启动预加载,以确保它在从zygote fork 32位relro进程之前完成。
// 如果花费太长时间,webview RELRO进程将阻止,但它没持有任何lock的情况下执行此操作。
mZygotePreload = SystemServerInitThreadPool.get().submit(() -> {
try {
Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
if (!Process.ZYGOTE_PROCESS.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) {
Slog.e(TAG, "Unable to preload default resources");
}
} catch (Exception ex) {
Slog.e(TAG, "Exception preloading default resources", ex);
}
}, SECONDARY_ZYGOTE_PRELOAD);
// 启动密钥验证应用id提供者服务KeyAttestationApplicationIdProviderService
ServiceManager.addService("sec_key_att_app_id_provider",
new KeyAttestationApplicationIdProviderService(context));
// 启动密钥链系统服务KeyChainSystemService
mSystemServiceManager.startService(KeyChainSystemService.class);
// 启动调度策略服务SchedulingPolicyService
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
// 启动电信加载服务TelecomLoaderService
mSystemServiceManager.startService(TelecomLoaderService.class);
// 启动通讯注册服务TelephonyRegistry
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry);
// 启动熵混合器服务EntropyMixer
mEntropyMixer = new EntropyMixer(context);
mContentResolver = context.getContentResolver();
// 必须在ContentService之前启动账户管理服务AccountManagerService
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
// 启动content服务ContentService
mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
// 安装系统提供者
mActivityManagerService.installSystemProviders();
// 重置SQLiteCompatibilityWalFlags
SQLiteCompatibilityWalFlags.reset();
// 记录错误和日志,例如wtf()。此服务间接依赖于SettingsProvider,需要在InstallSystemProviders之后执行此操作。
mSystemServiceManager.startService(DropBoxManagerService.class);
// 启动振动服务VibratorService
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
// 启动动态调用服务DynamicAndroidService
dynamicAndroid = new DynamicAndroidService(context);
ServiceManager.addService("dynamic_android", dynamicAndroid);
// 启动红外服务ConsumerIrService
if (!isWatch) {
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
}
// 启动唤醒服务AlarmManagerService
mSystemServiceManager.startService(AlarmManagerService.class);
// 获取Watchdog实例进行初始化
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
// 启动输入管理服务InputManagerService
inputManager = new InputManagerService(context);
// 启动窗口管理服务WindowManagerService
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
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();
// 开始接收来自HIDL服务的调用。
// 从单独的线程开始,因为它需要连接到SensorManager。这必须在START_SENSOR_SERVICE完成后启动。
SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);
// 启动VR相关服务VrManagerService
if (!isWatch && enableVrService) {
mSystemServiceManager.startService(VrManagerService.class);
}
inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
inputManager.start();
mDisplayManagerService.windowManagerAndInputReady();
// 如果有内核模拟器则跳过蓝牙。用于检查是否支持蓝牙。
if (isEmulator) {
Slog.i(TAG, "No Bluetooth Service (emulator)");
} else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
Slog.i(TAG, "No Bluetooth Service (factory test)");
} else if (!context.getPackageManager().hasSystemFeature
(PackageManager.FEATURE_BLUETOOTH)) {
Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
} else {
mSystemServiceManager.startService(BluetoothService.class);
}
// 启动IP通讯的服务IpConnectivityMetrics
mSystemServiceManager.startService(IpConnectivityMetrics.class);
// 启动网络监听列表的服务NetworkWatchlistService
mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
// 启动处理页面缓存(抖动)的服务PinnerService
mSystemServiceManager.startService(PinnerService.class);
} catch (RuntimeException e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service", e);
}
// 判断是否为安全模式,若是则打开飞行模式
final boolean safeMode = wm.detectSafeMode();
if (safeMode) {
Settings.Global.putInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 1);
}
...
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
// 启动输入法管理服务InputMethodManagerService
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
// 启动无障碍管理服务AccessibilityManagerService
try {
ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
new AccessibilityManagerService(context));
} catch (Throwable e) {
reportWtf("starting Accessibility Manager", e);
}
}
try {
wm.displayReady();
} catch (Throwable e) {
reportWtf("making display ready", e);
}
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
try {
// 先启动存储管理服务StorageManagerService,因为usb相关通知管理服务会依赖于它。
mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
storageManager = IStorageManager.Stub.asInterface(
ServiceManager.getService("mount"));
} catch (Throwable e) {
reportWtf("starting StorageManagerService", e);
}
// 启动存储统计服务StorageStatsService
try {
mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting StorageStatsService", e);
}
}
}
// 启动UI模式管理服务UiModeManagerService,以便为手表或者电视更新设置。
mSystemServiceManager.startService(UiModeManagerService.class);
if (!mOnlyCore) {
try {
mPackageManagerService.updatePackagesIfNeeded();
} catch (Throwable e) {
reportWtf("update packages", e);
}
}
try {
mPackageManagerService.performFstrimIfNeeded();
} catch (Throwable e) {
reportWtf("performing fstrim", e);
}
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
// 启动锁屏服务LockSettingsService
try {
mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
lockSettings = ILockSettings.Stub.asInterface(
ServiceManager.getService("lock_settings"));
} catch (Throwable e) {
reportWtf("starting LockSettingsService service", e);
}
final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
if (hasPdb) {
// 启动数据保护服务PersistentDataBlockService,用于存储Google账号等关键数据。
mSystemServiceManager.startService(PersistentDataBlockService.class);
}
if (hasPdb || OemLockService.isHalPresent()) {
// 启动OEM解锁服务OemLockService
mSystemServiceManager.startService(OemLockService.class);
}
// 启动设备待机控制服务DeviceIdleController
mSystemServiceManager.startService(DeviceIdleController.class);
// 启动设备策略管理服务DevicePolicyManagerService
mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
if (!isWatch) {
// 启动状态栏管理服务StatusBarManagerService
try {
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
} catch (Throwable e) {
reportWtf("starting StatusBarManagerService", e);
}
}
// 启动剪贴板服务ClipboardService
mSystemServiceManager.startService(ClipboardService.class);
try {
NetworkStackClient.getInstance().init();
} catch (Throwable e) {
reportWtf("initializing NetworkStackClient", e);
}
// 启动网络管理服务NetworkManagementService
try {
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
reportWtf("starting NetworkManagement Service", e);
}
// 启动IP安全服务IpSecService
try {
ipSecService = IpSecService.create(context);
ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService);
} catch (Throwable e) {
reportWtf("starting IpSec Service", e);
}
// 启动文本管理服务TextServicesManagerService
mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
// 启动文本分类管理服务TextClassificationManagerService
if (!disableSystemTextClassifier) {
mSystemServiceManager.startService(TextClassificationManagerService.Lifecycle.class);
}
// 启动网络分数服务NetworkScoreService
mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
// 启动网络统计服务NetworkStatsService
try {
networkStats = NetworkStatsService.create(context, networkManagement);
ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
} catch (Throwable e) {
reportWtf("starting NetworkStats Service", e);
}
// 启动网络策略管理服务NetworkPolicyManagerService
try {
networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
} catch (Throwable e) {
reportWtf("starting NetworkPolicy Service", e);
}
if (!mOnlyCore) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI)) {
// 启动WiFi服务WifiService
mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
// 启动WiFi扫描服务WifiScanningService
mSystemServiceManager.startService(
"com.android.server.wifi.scanner.WifiScanningService");
}
// 启动WiFi网络时延服务RttService
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_RTT)) {
mSystemServiceManager.startService(
"com.android.server.wifi.rtt.RttService");
}
// 启动WiFi感知服务WifiAwareService
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_AWARE)) {
mSystemServiceManager.startService(WIFI_AWARE_SERVICE_CLASS);
}
// 启动WiFi热点服务WifiP2pService
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_DIRECT)) {
mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
}
// 启动低功率无线网服务LowpanService
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_LOWPAN)) {
mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
}
}
// 启动以太网服务EthernetService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
}
// 启动数据链接管理服务ConnectivityService
try {
connectivity = new ConnectivityService(
context, networkManagement, networkStats, networkPolicy);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,
/* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
networkPolicy.bindConnectivityManager(connectivity);
} catch (Throwable e) {
reportWtf("starting Connectivity Service", e);
}
// 启动发现服务器网络服务NsdService
try {
serviceDiscovery = NsdService.create(context);
ServiceManager.addService(
Context.NSD_SERVICE, serviceDiscovery);
} catch (Throwable e) {
reportWtf("starting Service Discovery Service", e);
}
// 启动系统升级管理服务SystemUpdateManagerService
try {
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
new SystemUpdateManagerService(context));
} catch (Throwable e) {
reportWtf("starting SystemUpdateManagerService", e);
}
// 启动更新锁服务UpdateLockService
try {
ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
new UpdateLockService(context));
} catch (Throwable e) {
reportWtf("starting UpdateLockService", e);
}
// 启动通知管理服务NotificationManagerService
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
// 启动设备存储监听服务DeviceStorageMonitorService
mSystemServiceManager.startService(DeviceStorageMonitorService.class);
// 启动定位管理服务LocationManagerService
try {
location = new LocationManagerService(context);
ServiceManager.addService(Context.LOCATION_SERVICE, location);
} catch (Throwable e) {
reportWtf("starting Location Manager", e);
}
// 启动判断国家的服务CountryDetectorService
try {
countryDetector = new CountryDetectorService(context);
ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
} catch (Throwable e) {
reportWtf("starting Country Detector", e);
}
final boolean useNewTimeServices = true;
if (useNewTimeServices) {
// 启动时间探测服务TimeDetectorService
try {
mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting StartTimeDetectorService service", e);
}
}
if (!isWatch) {
// 启动搜索管理服务SearchManagerService
try {
mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting Search Service", e);
}
}
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
// 启动壁纸管理服务WallpaperManagerService
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
}
// 启动音频服务AudioService
mSystemServiceManager.startService(AudioService.Lifecycle.class);
// 启动广播电台服务BroadcastRadioService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
traceBeginAndSlog("StartBroadcastRadioService");
mSystemServiceManager.startService(BroadcastRadioService.class);
traceEnd();
}
// 启动DockObserver
mSystemServiceManager.startService(DockObserver.class);
// 启动ThermalObserver
if (isWatch) {
mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
}
// 启动音频外设管理服务WiredAccessoryManager
try {
// Listen for wired headset changes
inputManager.setWiredAccessoryCallbacks(
new WiredAccessoryManager(context, inputManager));
} catch (Throwable e) {
reportWtf("starting WiredAccessoryManager", e);
}
// 启动MidiService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
// Start MIDI Manager service
mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
}
// 启动UsbService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
|| mPackageManager.hasSystemFeature(
PackageManager.FEATURE_USB_ACCESSORY)
|| isEmulator) {
mSystemServiceManager.startService(USB_SERVICE_CLASS);
}
// 启动串口服务SerialService
if (!isWatch) {
try {
serial = new SerialService(context);
ServiceManager.addService(Context.SERIAL_SERVICE, serial);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting SerialService", e);
}
}
// 启动硬属性管理服务HardwarePropertiesManagerService
try {
hardwarePropertiesService = new HardwarePropertiesManagerService(context);
ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
hardwarePropertiesService);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
}
// 启动TwilightService
mSystemServiceManager.startService(TwilightService.class);
// 启动彩色显示服务ColorDisplayService
if (ColorDisplayController.isAvailable(context)) {
mSystemServiceManager.startService(ColorDisplayService.class);
}
// 启动任务安排服务JobSchedulerService
mSystemServiceManager.startService(JobSchedulerService.class);
// 启动语音识别服务SoundTriggerService
mSystemServiceManager.startService(SoundTriggerService.class);
// 启动TrustManagerService
mSystemServiceManager.startService(TrustManagerService.class);
// 启动备份管理服务BackupManagerService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
}
// 启动应用小部件服务AppWidgetService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
}
// 无论是否设置了FEATURE_VOICE_RECOGNIZERS功能,都需要始终启动VoiceInteractionManagerService服务
// 因为它需要负责初始化各种设置。它将在内部根据该功能修改其行为。
mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
// 启动手势服务GestureLauncherService
if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
mSystemServiceManager.startService(GestureLauncherService.class);
}
// 启动传感器通知服务SensorNotificationService
mSystemServiceManager.startService(SensorNotificationService.class);
// 启动ContextHubSystemService
mSystemServiceManager.startService(ContextHubSystemService.class);
// 启动磁盘统计服务DiskStatsService
try {
ServiceManager.addService("diskstats", new DiskStatsService(context));
} catch (Throwable e) {
reportWtf("starting DiskStats Service", e);
}
// 启动RuntimeService
try {
ServiceManager.addService("runtime", new RuntimeService(context));
} catch (Throwable e) {
reportWtf("starting RuntimeService", e);
}
// 如果安全时区更新所需的信任链被破坏,timezone.RulesManagerService将阻止设备启动。
// 当mOnlyCore==true时,RuleManagerService无法执行此检查,因此在这种情况下我们不启用该服务。
// JobSchedulerService启动前需已启动TimeZoneRulesManagerService
final boolean startRulesManagerService =
!mOnlyCore && context.getResources().getBoolean(
R.bool.config_enableUpdateableTimeZoneRules);
if (startRulesManagerService) {
mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS);
}
if (!isWatch) {
try {
if (useNewTimeServices) {
// 启动新的网络时间更新服务NewNetworkTimeUpdateService
networkTimeUpdater = new NewNetworkTimeUpdateService(context);
} else {
// 启动旧的网络时间更新服务OldNetworkTimeUpdateService
networkTimeUpdater = new OldNetworkTimeUpdateService(context);
}
Slog.d(TAG, "Using networkTimeUpdater class=" + networkTimeUpdater.getClass());
ServiceManager.addService("network_time_update_service", networkTimeUpdater);
} catch (Throwable e) {
reportWtf("starting NetworkTimeUpdate service", e);
}
}
try {
CertBlacklister blacklister = new CertBlacklister(context);
} catch (Throwable e) {
reportWtf("starting CertBlacklister", e);
}
// 启动紧急情况服务EmergencyAffordanceService
if (EmergencyAffordanceManager.ENABLED) {
mSystemServiceManager.startService(EmergencyAffordanceService.class);
}
// 启动DreamManagerService
mSystemServiceManager.startService(DreamManagerService.class);
// 启动图像统计服务GraphicsStatsService
ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
new GraphicsStatsService(context));
// 启动CoverageService
if (CoverageService.ENABLED) {
ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
}
// 启动打印管理PrintManagerService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
}
// 启动CompanionDeviceManagerService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
}
// 启动RestrictionsManagerService
mSystemServiceManager.startService(RestrictionsManagerService.class);
// 启动媒体会议服务MediaSessionService
mSystemServiceManager.startService(MediaSessionService.class);
// 启动媒体更新MediaUpdateService
mSystemServiceManager.startService(MediaUpdateService.class);
// 启动HDMI控制服务HdmiControlService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
mSystemServiceManager.startService(HdmiControlService.class);
}
// 启动TvInputManagerService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
mSystemServiceManager.startService(TvInputManagerService.class);
}
// 启动媒体资源监控服务MediaResourceMonitorService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
mSystemServiceManager.startService(MediaResourceMonitorService.class);
}
// 启动TvRemoteService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
mSystemServiceManager.startService(TvRemoteService.class);
}
// 启动媒体路由服务MediaRouterService
try {
mediaRouter = new MediaRouterService(context);
ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
} catch (Throwable e) {
reportWtf("starting MediaRouterService", e);
}
// 启动指纹服务FingerprintService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
mSystemServiceManager.startService(FingerprintService.class);
}
// 启动后台dex优化服务BackgroundDexOptService
try {
BackgroundDexOptService.schedule(context);
} catch (Throwable e) {
reportWtf("starting StartBackgroundDexOptService", e);
}
// 启动PruneInstantAppsJobService
try {
PruneInstantAppsJobService.schedule(context);
} catch (Throwable e) {
reportWtf("StartPruneInstantAppsJobService", e);
}
// 启动快捷方式服务ShortcutService
mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
// 启动桌面应用服务LauncherAppsService
mSystemServiceManager.startService(LauncherAppsService.class);
// 启动CrossProfileAppsService
mSystemServiceManager.startService(CrossProfileAppsService.class);
}
if (!isWatch) {
// 启动媒体投影管理服务MediaProjectionManagerService
mSystemServiceManager.startService(MediaProjectionManagerService.class);
}
if (isWatch) {
// 启动手表配置服务WearConfigService
mSystemServiceManager.startService(WEAR_CONFIG_SERVICE_CLASS);
// 启动手表通讯服务WearConnectivityService
mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
// 启动手表时间服务WearTimeService
mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
if (enableLeftyService) {
// 启动WearLeftyService
mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS);
}
// 启动WearGlobalActionsService
mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
}
// 启动SliceManagerService
if (!disableSlices) {
mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
}
// 启动CameraServiceProxy
if (!disableCameraService) {
mSystemServiceManager.startService(CameraServiceProxy.class);
}
// 启动IoTSystemService
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {
mSystemServiceManager.startService(IOT_SERVICE_CLASS);
}
// 启动StatsCompanionService
mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);
// 启动MmsServiceBroker
mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
// 启动AutofillManagerService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
}
...
// 此处告知ActivityManager可以运行第三方代码了。
// 一旦进入第三方代码可以真正运行的状态(但在实际开始启动初始应用程序之前),它将回调以便完成初始化。
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
// 监听Native Crash
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
...
// 启动SystemUI
try {
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
// 启动WatchDog
Watchdog.getInstance().start();
...
}, BOOT_TIMINGS_TRACE_LOG);
}

安卓中有一百多个系统服务,现整理如下表:

名称 作用
startBootstrapServices
Installer 应用的安装
DeviceIdentifiersPolicyService 处理设备标识符策略
ActivityManagerService 四大组件的启动、调度
PowerManagerService 管理Power
RecoverySystemService 处理recovery相关任务
LightsService LED背光的管理
SidekickService 滑盖的管理
DisplayManagerService 显示设备的管理
PackageManagerService 处理应用的安装、卸载等操作
UserManagerService 多用户模式的管理
OverlayManagerService overlay包的管理
SensorService 处理传感器相关任务
startCoreServices
BatteryService 统计电量
UsageStatsService 统计应用使用情况
WebViewUpdateService webview的更新
BinderCallsStatsService 统计binder调用
BugreportManagerService 统计bug报告
startOtherServices
KeyAttestationApplicationIdProviderService 密钥验证应用ID的管理
KeyChainSystemService 密钥链的管理
SchedulingPolicyService 策略的调度
TelecomLoaderService 加载Telecom控制通话逻辑
TelephonyRegistry 监听和管理通话事件和状态
EntropyMixer 处理加密相关任务
AccountManagerService 账户管理
ContentService ContentProvider更新通知
DropBoxManagerService 记录错误和日志
VibratorService 处理振动相关任务
DynamicAndroidService Android中动态调用
ConsumerIrService 处理红外线相关任务
AlarmManagerService 处理唤醒相关任务
InputManagerService 处理按键、触摸等输入操作
WindowManagerService 窗口管理
HidlServices 处理HIDL相关任务
VrManagerService VR管理
BluetoothService 处理蓝牙相关任务
IpConnectivityMetrics 处理IP通讯
NetworkWatchlistService 网络监听列表管理
PinnerService 页面抖动处理
InputMethodManagerService 输入法管理
AccessibilityManagerService 无障碍管理
StorageManagerService 存储管理
StorageStatsService 统计存储信息
UiModeManagerService 手表、电视UI管理
LockSettingsService 锁屏管理
PersistentDataBlockService 管理Google账号等关键数据
OemLockService 处理OEM解锁相关任务
DeviceIdleController 处理设备待机相关任务
DevicePolicyManagerService 设备策略管理
StatusBarManagerService 状态栏管理
ClipboardService 处理剪贴板相关任务
NetworkManagementService 网络管理
IpSecService IP安全管理
TextServicesManagerService 拼写检查等文本管理
TextClassificationManagerService 文本分类管理
NetworkScoreService 网络分数管理
NetworkStatsService 统计网络数据
NetworkPolicyManagerService 网络策略管理
WifiService WiFi管理
WifiScanningService WiFi扫描
RttService WiFi网络时延管理
WifiAwareService WiFi网络的感知
WifiP2pService WiFi热点管理
LowpanService 低功率无线网管理
EthernetService 以太网管理
ConnectivityService 数据链接管理
NsdService 发现服务器网络
SystemUpdateManagerService 管理系统升级
UpdateLockService 升级锁处理
NotificationManagerService 通知管理
DeviceStorageMonitorService 监听设备存储
LocationManagerService 定位管理
CountryDetectorService 判断所属国家
TimeDetectorService 时间监听器
SearchManagerService 搜索管理
WallpaperManagerService 壁纸管理
AudioService 音频管理
BroadcastRadioService 广播电台管理
DockObserver 负责监听Dock
ThermalObserver 监听thermal机制
WiredAccessoryManager 音频外设的管理
MidiService midi管理
UsbService usb管理
SerialService 串口管理
HardwarePropertiesManagerService 硬件属性管理
TwilightService 判断是否处于晚间
ColorDisplayService 彩色显示管理
JobSchedulerService Job的调度
SoundTriggerService 声音触发器
TrustManagerService 通信中trust管理
BackupManagerService 备份管理
AppWidgetService 应用小部件管理
VoiceInteractionManagerService 语音识别管理
GestureLauncherService 手势相关
SensorNotificationService 传感器通知
DiskStatsService 磁盘统计
RuntimeService 运行时状态
TimeZoneRulesManagerService 时区规则管理
NewNetworkTimeUpdateService 新的网络时间更新
OldNetworkTimeUpdateService 旧的网络时间更新
EmergencyAffordanceService 紧急情况
DreamManagerService 屏保管理
GraphicsStatsService 图像统计
PrintManagerService 打印管理
CompanionDeviceManagerService campanion设备管理
RestrictionsManagerService 用户限制管理
MediaSessionService 媒体会议
MediaUpdateService 媒体更新
HdmiControlService HDMI控制
TvInputManagerService TV输入管理
MediaResourceMonitorService 媒体资源监控
TvRemoteService TV遥控
MediaRouterService 媒体路由相关
FingerprintService 指纹相关
BackgroundDexOptService 后台dex优化
ShortcutService 桌面快捷方式相关
LauncherAppsService 桌面应用相关
MediaProjectionManagerService 媒体投影管理
CameraServiceProxy 相机相关
IoTSystemService IoT物联网系统
MmsServiceBroker mms短彩信相关
WearConfigService 手表配置相关
WearConnectivityService 手表通讯相关
WearTimeService 手表时间相关