[TOC]

文章从参考:https://jsonchao.github.io/2019/03/03/Android%E7%B3%BB%E7%BB%9F%E5%90%AF%E5%8A%A8%E6%B5%81%E4%B9%8BSystemServer%E8%BF%9B%E7%A8%8B%E5%90%AF%E5%8A%A8/

概述

其中Zygote进程由init进程启动,SystemServer进程和应用进程由Zygote进程启动。

SystemServer进程主要是用于创建系统服务的,例如AMS、WMS、PMS。这篇文章将从以下两个部分来对SystemServer进行分析:

  • Zygote处理SystemServer进程
  • SystemServer进程解析

SystemServer启动流程

SystemServer进程主要用于创建系统服务,我们熟悉的AMS、WMS、PMS都是由SystemServer创建的。关于这些系统服务我们后来再讲。本文我们先来熟悉并了解SystemServer进程是如何启动的,他在启动时做了哪些重要的工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
*/
@UnsupportedAppUsage
public static void main(String argv[]) {
// ......
//判断是否需要startSystemServer
if (startSystemServer) {
//通过fork的方式开启zygote的子进程,systemServer,并返回一个Runnale对象
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

// {@code r == null} in the parent (zygote) process, and {@code r != null} in the
// child (system_server) process.
//如果是zygote进程,则r==null,如果不是zygote进程,也就是systemServer进程,则执行下面的代码
if (r != null) {
r.run();
return;
}
}
// ......
}

由上面我们可以看出:在ZygoteInit的类中的main方法我们调用forkSystemServer来进行forkSystemServer的方法来进行fork出来SystemServer进程。并且执行其返回的Runnable的run()方法,我们先来看看forkSystemServer具体做了什么。

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
  private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
...
/* Hardcoded command line to start the system server */
// "通过硬编码的方式提供相关的参数"
String args[] = {
"--setuid=1000", //用户id
"--setgid=1000",//用户组id
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
+ "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities, //进程权能
"--nice-name=system_server", //进程niceName
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer", //需要启动的类
};
ZygoteArguments parsedArgs = null;

int pid; //processId,进程id

try {
parsedArgs = new ZygoteArguments(args); //"创建ZygoteArguments对象,把args解析为需要的参数"
Zygote.applyDebuggerSystemProperty(parsedArgs);
Zygote.applyInvokeWithSystemProperty(parsedArgs);

boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer) {
parsedArgs.mRuntimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}

/* Request to fork the system server process */
pid = Zygote.forkSystemServer( // "fork创建SystemServer"
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
...
}

Zygote#forkSystemServer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
//内部调用ART的Runtime对zygote的线程池的线程进行清理
ZygoteHooks.preFork();
//JNI调用,真正创建systemServer进程的函数
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);

// Set the Java Language thread priority to the default value for new apps.
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);

ZygoteHooks.postForkCommon();
return pid;
}

nativeForkSystemServer

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
 private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);

/**
* 代码位于:frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
* JNIEnv* env
**/
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities,
jlong effective_capabilities) {
// ......
//从zygote进程fork出子进程,并返回processId
pid_t pid = ForkCommon(env, true,
fds_to_close,
fds_to_ignore,
true);
if (pid == 0) {
// System server prcoess does not need data isolation so no need to
// know pkg_data_info_list.
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
permitted_capabilities, effective_capabilities,
MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr, /* is_top_app= */ false,
/* pkg_data_info_list */ nullptr,
/* whitelisted_data_info_list */ nullptr, false, false);
} else if (pid > 0) {
// ......
}
return pid;
}

com_android_internal_os_Zygote#ForkCommon

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
/**
* 代码位于:frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
* Utility routine to fork a process from the zygote.
* JNIEnv* env
**/
static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
const std::vector<int>& fds_to_close,
const std::vector<int>& fds_to_ignore,
bool is_priority_fork) {
SetSignalHandlers();

// Curry a failure function.
auto fail_fn = std::bind(ZygoteFailure, env, is_system_server ? "system_server" : "zygote",
nullptr, _1);

// ......
mallopt(M_PURGE, 0);
// 执行进程的Fork
pid_t pid = fork();

if (pid == 0) {
if (is_priority_fork) {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MAX);
} else {
setpriority(PRIO_PROCESS, 0, PROCESS_PRIORITY_MIN);
}


// ......
return pid;
}

ZygoteInit#handleSystemServerProcess

好了,别跑远了。咱们们继续回来看ZygoteInit.java的main方法。在我们forkSystem执行完毕之后,咱们开始调用handleSystemServerProcess方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 代码位于:/framework/base/core/java/com/android/internal/os/ZygoteInit.java
* Finish remaining work for the newly forked system server process.
*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
// set umask to 0077 so new files and directories will default to owner-only permissions.
//
/*
* Pass the remaining arguments to SystemServer.
* 将其余参数传递给SystemServer。
*/
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, cl);
}

/* should never reach here */
}

这个方法又调用到了ZygoteInit.zygoteInit()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges,
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();
// 调用Runtime的commonInit的方法
RuntimeInit.commonInit();
// 这个调用ZygoteInit的NativeZygoteInit()的方法
// 这个方法会调用到AndroidRuntime.cpp
ZygoteInit.nativeZygoteInit();
// 最终要的方法,调用的RuntimeInit.applicationInit()
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv,
classLoader);
}

nativeZygoteInit()

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
/**
* 代码位于:framwork/base/core/jni/AndroidRuntime.cpp
**/
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
// gCurRuntime是AndroidRuntime类型的指针,
// 具体指向的是其子类AppRuntime,它在app_main.cpp中定义
gCurRuntime->onZygoteInit();
}
/**
* 代码位于:framwork/base/core/jni/AndroidRuntime.cpp
**/
static void com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup(JNIEnv* env,
jobject clazz, jboolean exitWithoutCleanup)
{
gCurRuntime->setExitWithoutCleanup(exitWithoutCleanup);
}

/**
* 代码位于:framwork/base/core/jni/AndroidRuntime.cpp
* JNI registration.
**/
int register_com_android_internal_os_RuntimeInit(JNIEnv* env)
{
const JNINativeMethod methods[] = {
{"nativeFinishInit", "()V",
(void*)com_android_internal_os_RuntimeInit_nativeFinishInit},
{"nativeSetExitWithoutCleanup", "(Z)V",
(void*)com_android_internal_os_RuntimeInit_nativeSetExitWithoutCleanup},
};
return jniRegisterNativeMethods(env, "com/android/internal/os/RuntimeInit",
methods, NELEM(methods));
}

int register_com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env)
{
const JNINativeMethod methods[] = {
{ "nativeZygoteInit", "()V",
(void*) com_android_internal_os_ZygoteInit_nativeZygoteInit },
};
return jniRegisterNativeMethods(env, "com/android/internal/os/ZygoteInit",
methods, NELEM(methods));
}

gCurRuntime是AndroidRuntime类型的指针,具体指向的是其子类AppRuntime,它在app_main.cpp中定义,代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
/**
* 代码位于:framwork/base/cmds/app_process/app_main.cpp
**/
virtual void onZygoteInit(){
// 创建了一个ProcessState实例, 在Android中ProcessState是客户端和服务端公共的部分,
// 作为Binder通信的基础,ProcessState是一个singleton类,每个进程只有一个对象,这个对象负责打开Binder驱动,建立线程池,
// 让其进程里面的所有线程都能通过Binder通信。
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}

创建了一个ProcessState实例, 在Android中ProcessState是客户端和服务端公共的部分,作为Binder通信的基础,ProcessState是一个singleton类,每个
进程只有一个对象,这个对象负责打开Binder驱动,建立线程池,让其进程里面的所有线程都能通过Binder通信。在注释2处,调用了ProcessState实例的startThreadPool()函数启动了一个Binder线程池,其实里面最终会调用到IPCThreadState实例的joinThreadPool()函数进程Binder线程池相关的处理。

好的,我们再回过来看ZygoteInit.zygoteInit()的方法。最后一行调用下面的方法。

RuntimeInit.applicationInit()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges,
String[] argv, ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
// Android runtime shutdown hooks close the Binder driver, which can cause
// leftover running threads to crash before the process actually exits.
nativeSetExitWithoutCleanup(true);

VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
VMRuntime.getRuntime().setDisabledCompatChanges(disabledCompatChanges);
// 进行参数的封装解析
final Arguments args = new Arguments(argv);

// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);

// Remaining arguments are passed to the start class's static main
// 调用main方法。并将参数传入过去
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
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

/**
* 代码位于:/framework/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);
}

/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
return new MethodAndArgsCaller(m, argv);
}

代码到这里,就比较清晰明了了、这个地方就是会通过反射调用到SystemServer的main方法。

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
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
/**
* 代码位于:/framework/base/core/java/com/android/server/SystemServer.java
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
/**
* 代码位于:/framework/base/core/java/com/android/server/SystemServer.java
*/
public SystemServer() {
// Check for factory test mode.
mFactoryTestMode = FactoryTest.getMode();

// Record process start information.
// Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots;
// one for the password screen, second for the actual boot.
mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1;
mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
mRuntimeStartUptime = SystemClock.uptimeMillis();
Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime);

// Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
// We don't use "mStartCount > 1" here because it'll be wrong on a FDE device.
// TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before
// sys.boot_completed is set. Fix it.
mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
}
/**
* 代码位于:/framework/base/core/java/com/android/server/SystemServer.java
*/
private void run() {
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
try {
// ......

// 创建主线程Looper
Looper.prepareMainLooper();
//
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

SystemServiceRegistry.sEnableServiceNotFoundWtf = true;

// Initialize native services.
// 加载了动态库libandroid_servers.so
System.loadLibrary("android_servers");

// Allow heap / perf profiling.
initZygoteChildHeapProfiling();

// Debug builds - spawn a thread to monitor for fd leaks.
if (Build.IS_DEBUGGABLE) {
spawnFdLeakCheckThread();
}

// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();

// Initialize the system context.
// 创建上下文对象
createSystemContext();

// Call per-process mainline module initialization.
ActivityThread.initializeMainlineModules();

// Create the system service manager.
// 创建SystemServiceManager.对系统服务进行创建、启动和生命周期管理。
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.start();
// ......
} finally {
t.traceEnd(); // InitBeforeStartServices
}

// Setup the default WTF handler
RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);

// Start services.
try {
t.traceBegin("StartServices");
// startBootstarpServices()方法中
// 使用SystemServiceManager启动了ActivityManagerService、PackageManagerService、PowerManagerService等引导服务。
startBootstrapServices(t);
// startCoreServices()方法启动了BatteryService、WebViewUpdateService、DropBoxManagerService、UsageStatsService4个核心服务
startCoreServices(t);
// startOtherServices()方法中启动了WindowManagerService、InputManagerService、CameraService等其它服务。
startOtherServices(t);
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}

StrictMode.initVmDefaults(null);

// ......

// Loop forever. 执行无限循环的Loop方法
Looper.loop();
// 正常情况下下面你的语句永远都不会执行到
throw new RuntimeException("Main thread loop unexpectedly exited");
}

上面是SystemServer类的启动方法的整体代码逻辑。里面会启动BootstrapServices、CoreServices、OtherServices 同时会创建SystemServer的主线程Looper。然后执行loop方法。

下面我们就看SystemServer是怎么启动这些系统的Services的。

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
/**
* 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(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startBootstrapServices");

t.traceBegin("StartWatchdog");
// 启动看门狗服务
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();

// 读取系统配置
SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

// FileIntegrityService responds to requests from apps and the system. It needs to run after
// the source (i.e. keystore) is ready, and before the apps (or the first customer in the
// system) run.
// 启动文件完整性服务
t.traceBegin("StartFileIntegrityService");
mSystemServiceManager.startService(FileIntegrityService.class);
t.traceEnd();

Installer installer = mSystemServiceManager.startService(Installer.class);

// 启动PowerManagerService
t.traceBegin("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
t.traceEnd();

// 启动ActivityTaskManagerService服务。这个服务比较重要
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();


// 启动PackageManagerService
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
mDataLoaderManagerService = mSystemServiceManager.startService(
DataLoaderManagerService.class);
t.traceEnd();
// ......
}

我们日志代码中可以看到引导服务主要会启动:看门狗、读取系统配置、启动文件完整性服务、启动ActivityTaskManagerService、PackageManagerService、PowerManagerService。

  • 引导服务:ActivityTaskManagerService,这个服务比较重要。负责四大组件的启动、切换、调度。

  • 引导服务:PackageManagerService,负责对APK进行安装、解析、删除、卸载等操作。

  • 引导服务:PowerManagerService,负责计算系统中与Power相关的计算,然后决定系统该如何反应。

SystemServer#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
/**
* 代码位于:/framework/base/core/java/com/android/server/SystemServer.java
* 启动引导此过程中,没有启动的一些核心服务
*/
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startCoreServices");

// 启动系统配置服务
t.traceBegin("StartSystemConfigService");
mSystemServiceManager.startService(SystemConfigService.class);
t.traceEnd();

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

// ......

// 启动GPU 和 GPU驱动的服务
t.traceBegin("GpuService");
mSystemServiceManager.startService(GpuService.class);
t.traceEnd();

t.traceEnd(); // startCoreServices
}
  • 核心服务:BatteryService,管理电池相关的服务。
  • 核心服务:SystemConfigService,系统配置相关的服务。

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
 private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startOtherServices");
// 系统上下文对象
final Context context = mSystemContext;
VibratorService vibrator = null;
DynamicSystemService dynamicSystem = null;
IStorageManager storageManager = null;
NetworkManagementService networkManagement = null;
IpSecService ipSecService = null;
NetworkStatsService networkStats = null;
NetworkPolicyManagerService networkPolicy = null;
ConnectivityService connectivity = null;
NsdService serviceDiscovery = null;
// WindowManagerService,简称WMS
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
// InputManagerService, 简称IMS
InputManagerService inputManager = null;
TelephonyRegistry telephonyRegistry = null;
ConsumerIrService consumerIr = null;
MmsServiceBroker mmsService = null;
HardwarePropertiesManagerService hardwarePropertiesService = null;

//......
// 实例化InputManagerService
t.traceBegin("StartInputManagerService");
inputManager = new InputManagerService(context);
t.traceEnd();

// 启动WindowManagerService
t.traceBegin("StartWindowManagerService");
// WMS needs sensor service ready
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
// InputManagerService和WindowManagerService进行绑定起来
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
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);
t.traceEnd();

t.traceBegin("SetWindowManagerService");
mActivityManagerService.setWindowManager(wm);
t.traceEnd();

t.traceBegin("WindowManagerServiceOnInitReady");
wm.onInitReady();
t.traceEnd();

// Start receiving calls from HIDL services. Start in in a separate thread
// because it need to connect to SensorManager. This have to start
// after START_SENSOR_SERVICE is done.
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);

if (!isWatch && enableVrService) {
t.traceBegin("StartVrManagerService");
mSystemServiceManager.startService(VrManagerService.class);
t.traceEnd();
}

t.traceBegin("StartInputManager");
// 给inputManager增加WindowManager的监听回调
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
// 启动IputManager
inputManager.start();
t.traceEnd();
//.....
}