浅析SystemServer进程

前引

  • 在android framework或者应用程序开发中所需要的主要API都是以系统服务的形式存在的,例如获取终端的当前位置,读取感应器的数值,拨打电话等,这些基本的功能在framework中都是以服务的形式存在的。

  • 在android系统中,服务是没有UI界面的,它作为一个后台进程,周期性地执行某些特定任务。在开发一些用于处理无需用户干预的数据的后台应用程序时,经常会使用这类android应用程序服务,例如通过网络对数据进行周期性的监控,或接收RSS反馈分析XML数据。在开发android程序时,引入适当的服务,从而开发出更灵活、更健康、更便捷的优秀程序来。

  • android服务的种类主要有两类,一类是系统服务,它们是由framework提供的;另一类是应用程序服务,它们是应用程序开发者继承并实现Service类后开发出来的。

    android服务分类

SystemServer系统服务概要

  • SystemServer服务进程是android系统Java层框架的核心,它维护这android的核心服务,比如AMS、WMS、PMS等,是android系统中一个非常重要的进程。

  • init进程、zygote进程和SystemServer进程都非常重要,因为其中任何一个系统死机都会重启。在android系统中,应用程序出现问题,对系统的影响不大,因为应用程序出现问题不会引起系统重启。

  • init进程、zygote进程和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
    private static boolean startSystemServer(String abiList, String socketName)
    throws MethodAndArgsCaller, RuntimeException {
    long capabilities = posixCapabilitiesAsBits(
    OsConstants.CAP_IPC_LOCK,
    OsConstants.CAP_KILL,
    OsConstants.CAP_NET_ADMIN,
    OsConstants.CAP_NET_BIND_SERVICE,
    OsConstants.CAP_NET_BROADCAST,
    OsConstants.CAP_NET_RAW,
    OsConstants.CAP_SYS_MODULE,
    OsConstants.CAP_SYS_NICE,
    OsConstants.CAP_SYS_RESOURCE,
    OsConstants.CAP_SYS_TIME,
    OsConstants.CAP_SYS_TTY_CONFIG
    );
    if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
    capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
    }
    String args[] = {
    "--setuid=1000",
    "--setgid=1000",
    "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
    "--capabilities=" + capabilities + "," + capabilities,
    "--nice-name=system_server",
    "--runtime-args",
    "com.android.server.SystemServer",
    };
    ZygoteConnection.Arguments parsedArgs = null;
    int pid;
    try {
    parsedArgs = new ZygoteConnection.Arguments(args);
    ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
    ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
    //
    pid = Zygote.forkSystemServer(
    parsedArgs.uid, parsedArgs.gid,
    parsedArgs.gids,
    parsedArgs.debugFlags,
    null,
    parsedArgs.permittedCapabilities,
    parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
    throw new RuntimeException(ex);
    }
    if (pid == 0) {
    if (hasSecondZygote(abiList)) {
    waitForSecondaryZygote(socketName);
    }
    handleSystemServerProcess(parsedArgs);
    }
    return true;
    }

    SystemServer系统服务进程是由zygote进程启动的,从ZygoteInit类的startSystemServer()方法开始,在startSystemServer()方法中调用了两个方法,分别是zygote的forkSystemServer()方法和handleSystemServerProcess()方法,其中,handleSystemServerProcess()是子进程即SystemServer进程的方法,而forkSystemServer()方法是在父进程即zygote进程的方法,handleSystemServerProcess()在android启动过程分析——zygote进程已经分析过了,接下来就来分析forkSystemServer()这个方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
    int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
    VM_HOOKS.preFork();
    int pid = nativeForkSystemServer(
    uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
    if (pid == 0) {
    Trace.setTracingEnabled(true);
    }
    VM_HOOKS.postForkCommon();
    return pid;
    }

    forkSystemServer()方法调用了nativeForkSystemServer()方法来做进一步处理,它是一个native的方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    static jint com_android_internal_os_Zygote_nativeForkSystemServer(
    JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
    jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,
    jlong effectiveCapabilities) {
    // 传入众多参数来fork一个新的进程
    pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
    debug_flags, rlimits,
    permittedCapabilities, effectiveCapabilities,
    MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
    NULL, NULL);
    if (pid > 0) {
    ALOGI("System server process %d has been created", pid);
    gSystemServerPid = pid;
    int status;
    if (waitpid(pid, &status, WNOHANG) == pid) {
    ALOGE("System server process %d has died. Restarting Zygote!", pid);
    RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
    }
    }
    return pid;
    }

    在这个jni文件里的com_android_internal_os_Zygote_nativeForkSystemServer函数调用了ForkAndSpecializeCommon()函数来做进一步操作。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
    jint debug_flags, jobjectArray javaRlimits,
    jlong permittedCapabilities, jlong effectiveCapabilities,
    jint mount_external,
    jstring java_se_info, jstring java_se_name,
    bool is_system_server, jintArray fdsToClose,
    jstring instructionSet, jstring dataDir) {
    SetSigChldHandler();
    ....
    pid_t pid = fork();
    .......
    return pid;
    }

    ForkAndSpecializeCommon()函数调用了两个非常重要的函数,分别是SetSigChldHandler()函数和fork()函数,fork()函数用来创建一个新的子进程,SetSigChldHandler()函数设置了信号处理函数SigChldHandler。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    static void SetSigChldHandler() {
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    // 当子进程死亡之后,就会产生一个信号,zygote进程收到这个信号之后就会调用SigChldHandler()函数处理。
    sa.sa_handler = SigChldHandler;
    int err = sigaction(SIGCHLD, &sa, NULL);
    if (err < 0) {
    ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
    }
    }

    接下来看看SigChldHandler()函数信号处理函数捕获异常的实现。

    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
    static void SigChldHandler(int /*signal_number*/) {
    pid_t pid;
    int status;
    int saved_errno = errno;
    while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
    if (WIFEXITED(status)) {
    if (WEXITSTATUS(status)) {
    ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));
    }
    } else if (WIFSIGNALED(status)) {
    if (WTERMSIG(status) != SIGKILL) {
    ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));
    }
    if (WCOREDUMP(status)) {
    ALOGI("Process %d dumped core.", pid);
    }
    }
    // gSystemServerPid表示SystemServer进程的pid,前面已经为它赋过值了。如果SystemServer进程停止工作,首先通过getpid()来获取zygote进程的pid,然后调用kill函数杀死它。即SystemServer停止工作后,zygote自杀,以达到zygote与SystemServer生死与共的目的
    if (pid == gSystemServerPid) {
    ALOGE("Exit zygote because system server (%d) has terminated", pid);
    kill(getpid(), SIGKILL);
    }
    }
    if (pid < 0 && errno != ECHILD) {
    ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));
    }
    errno = saved_errno;
    }

    最后会看一下init进程的main()函数里的死循环,如果它的子进程zygote停止工作,就会去重启子进程。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    int main(int argc, char** argv) {
    ...
    while (true) {
    if (!waiting_for_exec) {
    // 执行子进程对应的命令,即执行init.rc文件里配置的命令
    am.ExecuteOneCommand();
    // 这个函数用于重启死掉的service
    restart_processes();
    }
    ...
    }
    ...
    }

    从上面的过程可知,init进程、zygote进程、SystemServer进程紧密相连,任何一个都不能出问题。

SystemServer创建框架核心服务

  • SystemServer进程在android运行环境中扮演着“神经中枢”的作用,APK应用中能够直接交互的大部分系统服务都在该进程中运行,它创建了很多android系统核心服务,核心服务比如AMS、WMS、PMS等,这些系统服务都是以一个线程的方式存在于SystemServer进程中。

    SystemServer的服务

  • SystemServer进程由zygote进程创建,它是zygote进程的子进程,也是zygote的第一个子进程。当SystemServer启动后,就会进入main()方法,又在它的main()方法中调用run()方法。android系统的核心服务AMS、WMS、PMS等都是在run()方法中进行创建和初始化,当它们创建之后,会通过ServiceManager的add_service()方法把它们加入到ServiceManager中统一管理。

  • SystemServer创建服务的大致流程如下:

    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
    public final class SystemServer {
    ...
    public static void main(String[] args) {
    new SystemServer().run();
    }
    public SystemServer() {
    mFactoryTestMode = FactoryTest.getMode();
    }
    private void run() {
    try {
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");
    if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
    Slog.w(TAG, "System clock is before 1970; setting to 1970.");
    SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
    }
    if (!SystemProperties.get("persist.sys.language").isEmpty()) {
    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", "");
    }
    Slog.i(TAG, "Entered the Android system server!");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());
    SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
    if (SamplingProfilerIntegration.isEnabled()) {
    SamplingProfilerIntegration.start();
    mProfilerSnapshotTimer = new Timer();
    mProfilerSnapshotTimer.schedule(new TimerTask() {
    @Override
    public void run() {
    SamplingProfilerIntegration.writeSnapshot("system_server", null);
    }
    }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    }
    VMRuntime.getRuntime().clearGrowthLimit();
    VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
    Build.ensureFingerprintProperty();
    Environment.setUserRequired(true);
    BaseBundle.setShouldDefuse(true);
    BinderInternal.disableBackgroundScheduling(true);
    BinderInternal.setMaxThreads(sMaxBinderThreads);
    // 设置SystemServer进程线程的优先级,这个优先级非常高
    android.os.Process.setThreadPriority(
    android.os.Process.THREAD_PRIORITY_FOREGROUND);
    android.os.Process.setCanSelfBackground(false);
    // 创建消息队列
    Looper.prepareMainLooper();
    // 加载SystemServer需要的android_servers库
    System.loadLibrary("android_servers");
    performPendingShutdown();
    // 创建系统Context
    createSystemContext();
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    } finally {
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    try {
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
    // 接下来这三个方法是创建系统核心服务的实现
    startBootstrapServices();
    startCoreServices();
    startOtherServices();
    } catch (Throwable ex) {
    Slog.e("System", "******************************************");
    Slog.e("System", "************ Failure starting system services", ex);
    throw ex;
    } finally {
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (StrictMode.conditionallyEnableDebugLogging()) {
    Slog.i(TAG, "Enabled StrictMode for system server main thread.");
    }
    // 进入消息循环
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    ...
    }

    run()方法调用了三个非常重要的方法来创建和启动核心服务,分别是startBootstrapServices(),startCoreServices(), 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
    private void startBootstrapServices() {
    // installer链接installd,请求installd安装apk
    Installer installer = mSystemServiceManager.startService(Installer.class);
    // 启动ActivityManagerService服务
    mActivityManagerService = mSystemServiceManager.startService(
    ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    // 启动电源管理服务
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");
    mActivityManagerService.initPowerManagement();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    mSystemServiceManager.startService(LightsService.class);
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    String cryptState = SystemProperties.get("vold.decrypt");
    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;
    }
    traceBeginAndSlog("StartPackageManagerService");
    // 启动PackageManagerService服务,用来安装apk,分配权限
    mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
    mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    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 {
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    }
    }
    traceBeginAndSlog("StartUserManagerService");
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    AttributeCache.init(mSystemContext);
    mActivityManagerService.setSystemProcess();
    startSensorService();
    }

    startBootstrapServices()用来启动一些critical服务,这些服务有着复杂的互相依赖关系,所以把它们放在一个地方初始化。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    private void startCoreServices() {
    mSystemServiceManager.startService(BatteryService.class);
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
    LocalServices.getService(UsageStatsManagerInternal.class));
    mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

    startCoreServices()启动的是一些重要服务,如BatteryService,UsageStatsService等。

    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
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    private void startOtherServices() {
    final Context context = mSystemContext;
    VibratorService vibrator = null;
    IMountService mountService = null;
    NetworkManagementService networkManagement = null;
    NetworkStatsService networkStats = null;
    NetworkPolicyManagerService networkPolicy = null;
    ConnectivityService connectivity = null;
    NetworkScoreService networkScore = null;
    NsdService serviceDiscovery= null;
    WindowManagerService wm = null;
    SerialService serial = null;
    NetworkTimeUpdateService networkTimeUpdater = null;
    CommonTimeManagementService commonTimeMgmtService = null;
    InputManagerService inputManager = null;
    TelephonyRegistry telephonyRegistry = null;
    ConsumerIrService consumerIr = null;
    MmsServiceBroker mmsService = null;
    HardwarePropertiesManagerService hardwarePropertiesService = null;
    boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);
    boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);
    boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);
    boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);
    boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);
    boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);
    boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);
    boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false);
    boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj",
    false);
    boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false);
    boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager",
    false);
    boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",
    false);
    boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false);
    boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",
    false);
    boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
    try {
    Slog.i(TAG, "Reading configuration...");
    SystemConfig.getInstance();
    traceBeginAndSlog("StartSchedulingPolicyService");
    ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    mSystemServiceManager.startService(TelecomLoaderService.class);
    traceBeginAndSlog("StartTelephonyRegistry");
    telephonyRegistry = new TelephonyRegistry(context);
    ServiceManager.addService("telephony.registry", telephonyRegistry);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartEntropyMixer");
    mEntropyMixer = new EntropyMixer(context);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    mContentResolver = context.getContentResolver();
    Slog.i(TAG, "Camera Service");
    mSystemServiceManager.startService(CameraService.class);
    traceBeginAndSlog("StartAccountManagerService");
    mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartContentService");
    mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("InstallSystemProviders");
    mActivityManagerService.installSystemProviders();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartVibratorService");
    vibrator = new VibratorService(context);
    ServiceManager.addService("vibrator", vibrator);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartConsumerIrService");
    consumerIr = new ConsumerIrService(context);
    ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartAlarmManagerService");
    mSystemServiceManager.startService(AlarmManagerService.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("InitWatchdog");
    final Watchdog watchdog = Watchdog.getInstance();
    watchdog.init(context, mActivityManagerService);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartInputManagerService");
    inputManager = new InputManagerService(context);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartWindowManagerService");
    wm = WindowManagerService.main(context, inputManager,
    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
    !mFirstBoot, mOnlyCore);
    ServiceManager.addService(Context.WINDOW_SERVICE, wm);
    ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartVrManagerService");
    mSystemServiceManager.startService(VrManagerService.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    mActivityManagerService.setWindowManager(wm);
    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 if (disableBluetooth) {
    Slog.i(TAG, "Bluetooth Service disabled by config");
    } else {
    mSystemServiceManager.startService(BluetoothService.class);
    }
    traceBeginAndSlog("ConnectivityMetricsLoggerService");
    mSystemServiceManager.startService(MetricsLoggerService.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("PinnerService");
    mSystemServiceManager.startService(PinnerService.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    } catch (RuntimeException e) {
    Slog.e("System", "******************************************");
    Slog.e("System", "************ Failure starting core service", e);
    }
    StatusBarManagerService statusBar = null;
    INotificationManager notification = null;
    LocationManagerService location = null;
    CountryDetectorService countryDetector = null;
    ILockSettings lockSettings = null;
    AssetAtlasService atlas = null;
    MediaRouterService mediaRouter = null;
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
    traceBeginAndSlog("StartAccessibilityManagerService");
    try {
    ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
    new AccessibilityManagerService(context));
    } catch (Throwable e) {
    reportWtf("starting Accessibility Manager", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    try {
    wm.displayReady();
    } catch (Throwable e) {
    reportWtf("making display ready", e);
    }
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    if (!disableStorage &&
    !"0".equals(SystemProperties.get("system_init.startmountservice"))) {
    try {
    mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);
    mountService = IMountService.Stub.asInterface(
    ServiceManager.getService("mount"));
    } catch (Throwable e) {
    reportWtf("starting Mount Service", e);
    }
    }
    }
    mSystemServiceManager.startService(UiModeManagerService.class);
    if (!mOnlyCore) {
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded");
    try {
    mPackageManagerService.updatePackagesIfNeeded();
    } catch (Throwable e) {
    reportWtf("update packages", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded");
    try {
    mPackageManagerService.performFstrimIfNeeded();
    } catch (Throwable e) {
    reportWtf("performing fstrim", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    try {
    ActivityManagerNative.getDefault().showBootMessage(
    context.getResources().getText(
    com.android.internal.R.string.android_upgrading_starting_apps),
    false);
    } catch (RemoteException e) {
    }
    if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    if (!disableNonCoreServices) {
    traceBeginAndSlog("StartLockSettingsService");
    try {
    mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
    lockSettings = ILockSettings.Stub.asInterface(
    ServiceManager.getService("lock_settings"));
    } catch (Throwable e) {
    reportWtf("starting LockSettingsService service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {
    mSystemServiceManager.startService(PersistentDataBlockService.class);
    }
    mSystemServiceManager.startService(DeviceIdleController.class);
    mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
    }
    if (!disableSystemUI) {
    traceBeginAndSlog("StartStatusBarManagerService");
    try {
    statusBar = new StatusBarManagerService(context, wm);
    ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
    } catch (Throwable e) {
    reportWtf("starting StatusBarManagerService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices) {
    traceBeginAndSlog("StartClipboardService");
    try {
    ServiceManager.addService(Context.CLIPBOARD_SERVICE,
    new ClipboardService(context));
    } catch (Throwable e) {
    reportWtf("starting Clipboard Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNetwork) {
    traceBeginAndSlog("StartNetworkManagementService");
    try {
    networkManagement = NetworkManagementService.create(context);
    ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
    } catch (Throwable e) {
    reportWtf("starting NetworkManagement Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices && !disableTextServices) {
    mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
    }
    if (!disableNetwork) {
    traceBeginAndSlog("StartNetworkScoreService");
    try {
    networkScore = new NetworkScoreService(context);
    ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);
    } catch (Throwable e) {
    reportWtf("starting Network Score Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartNetworkStatsService");
    try {
    networkStats = NetworkStatsService.create(context, networkManagement);
    ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
    } catch (Throwable e) {
    reportWtf("starting NetworkStats Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartNetworkPolicyManagerService");
    try {
    networkPolicy = new NetworkPolicyManagerService(
    context, mActivityManagerService,
    (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE),
    networkStats, networkManagement);
    ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
    } catch (Throwable e) {
    reportWtf("starting NetworkPolicy Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {
    mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);
    } else {
    Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");
    }
    mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
    mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
    mSystemServiceManager.startService(
    "com.android.server.wifi.scanner.WifiScanningService");
    if (!disableRtt) {
    mSystemServiceManager.startService("com.android.server.wifi.RttService");
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
    mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
    mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
    }
    traceBeginAndSlog("StartConnectivityService");
    try {
    connectivity = new ConnectivityService(
    context, networkManagement, networkStats, networkPolicy);
    ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
    networkStats.bindConnectivityManager(connectivity);
    networkPolicy.bindConnectivityManager(connectivity);
    } catch (Throwable e) {
    reportWtf("starting Connectivity Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartNsdService");
    try {
    serviceDiscovery = NsdService.create(context);
    ServiceManager.addService(
    Context.NSD_SERVICE, serviceDiscovery);
    } catch (Throwable e) {
    reportWtf("starting Service Discovery Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices) {
    traceBeginAndSlog("StartUpdateLockService");
    try {
    ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
    new UpdateLockService(context));
    } catch (Throwable e) {
    reportWtf("starting UpdateLockService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices) {
    mSystemServiceManager.startService(RecoverySystemService.class);
    }
    if (mountService != null && !mOnlyCore) {
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WaitForAsecScan");
    try {
    mountService.waitForAsecScan();
    } catch (RemoteException ignored) {
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    mSystemServiceManager.startService(NotificationManagerService.class);
    notification = INotificationManager.Stub.asInterface(
    ServiceManager.getService(Context.NOTIFICATION_SERVICE));
    networkPolicy.bindNotificationManager(notification);
    mSystemServiceManager.startService(DeviceStorageMonitorService.class);
    if (!disableLocation) {
    traceBeginAndSlog("StartLocationManagerService");
    try {
    location = new LocationManagerService(context);
    ServiceManager.addService(Context.LOCATION_SERVICE, location);
    } catch (Throwable e) {
    reportWtf("starting Location Manager", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    traceBeginAndSlog("StartCountryDetectorService");
    try {
    countryDetector = new CountryDetectorService(context);
    ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
    } catch (Throwable e) {
    reportWtf("starting Country Detector", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices && !disableSearchManager) {
    traceBeginAndSlog("StartSearchManagerService");
    try {
    mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
    } catch (Throwable e) {
    reportWtf("starting Search Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    mSystemServiceManager.startService(DropBoxManagerService.class);
    if (!disableNonCoreServices && context.getResources().getBoolean(
    R.bool.config_enableWallpaperService)) {
    traceBeginAndSlog("StartWallpaperManagerService");
    mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    traceBeginAndSlog("StartAudioService");
    mSystemServiceManager.startService(AudioService.Lifecycle.class);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!disableNonCoreServices) {
    mSystemServiceManager.startService(DockObserver.class);
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
    mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
    }
    }
    traceBeginAndSlog("StartWiredAccessoryManager");
    try {
    inputManager.setWiredAccessoryCallbacks(
    new WiredAccessoryManager(context, inputManager));
    } catch (Throwable e) {
    reportWtf("starting WiredAccessoryManager", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!disableNonCoreServices) {
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
    mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
    || mPackageManager.hasSystemFeature(
    PackageManager.FEATURE_USB_ACCESSORY)) {
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartUsbService");
    mSystemServiceManager.startService(USB_SERVICE_CLASS);
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableSerial) {
    traceBeginAndSlog("StartSerialService");
    try {
    serial = new SerialService(context);
    ServiceManager.addService(Context.SERIAL_SERVICE, serial);
    } catch (Throwable e) {
    Slog.e(TAG, "Failure starting SerialService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER,
    "StartHardwarePropertiesManagerService");
    try {
    hardwarePropertiesService = new HardwarePropertiesManagerService(context);
    ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
    hardwarePropertiesService);
    } catch (Throwable e) {
    Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    mSystemServiceManager.startService(TwilightService.class);
    mSystemServiceManager.startService(JobSchedulerService.class);
    mSystemServiceManager.startService(SoundTriggerService.class);
    if (!disableNonCoreServices) {
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
    mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
    || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
    mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {
    mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
    }
    if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
    Slog.i(TAG, "Gesture Launcher Service");
    mSystemServiceManager.startService(GestureLauncherService.class);
    }
    mSystemServiceManager.startService(SensorNotificationService.class);
    mSystemServiceManager.startService(ContextHubSystemService.class);
    }
    traceBeginAndSlog("StartDiskStatsService");
    try {
    ServiceManager.addService("diskstats", new DiskStatsService(context));
    } catch (Throwable e) {
    reportWtf("starting DiskStats Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!disableSamplingProfiler) {
    traceBeginAndSlog("StartSamplingProfilerService");
    try {
    ServiceManager.addService("samplingprofiler",
    new SamplingProfilerService(context));
    } catch (Throwable e) {
    reportWtf("starting SamplingProfiler Service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNetwork && !disableNetworkTime) {
    traceBeginAndSlog("StartNetworkTimeUpdateService");
    try {
    networkTimeUpdater = new NetworkTimeUpdateService(context);
    ServiceManager.addService("network_time_update_service", networkTimeUpdater);
    } catch (Throwable e) {
    reportWtf("starting NetworkTimeUpdate service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    traceBeginAndSlog("StartCommonTimeManagementService");
    try {
    commonTimeMgmtService = new CommonTimeManagementService(context);
    ServiceManager.addService("commontime_management", commonTimeMgmtService);
    } catch (Throwable e) {
    reportWtf("starting CommonTimeManagementService service", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!disableNetwork) {
    traceBeginAndSlog("CertBlacklister");
    try {
    CertBlacklister blacklister = new CertBlacklister(context);
    } catch (Throwable e) {
    reportWtf("starting CertBlacklister", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices) {
    mSystemServiceManager.startService(DreamManagerService.class);
    }
    if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {
    traceBeginAndSlog("StartAssetAtlasService");
    try {
    atlas = new AssetAtlasService(context);
    ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);
    } catch (Throwable e) {
    reportWtf("starting AssetAtlasService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    if (!disableNonCoreServices) {
    ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
    new GraphicsStatsService(context));
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
    mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
    }
    mSystemServiceManager.startService(RestrictionsManagerService.class);
    mSystemServiceManager.startService(MediaSessionService.class);
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
    mSystemServiceManager.startService(HdmiControlService.class);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {
    mSystemServiceManager.startService(TvInputManagerService.class);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
    mSystemServiceManager.startService(MediaResourceMonitorService.class);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
    mSystemServiceManager.startService(TvRemoteService.class);
    }
    if (!disableNonCoreServices) {
    traceBeginAndSlog("StartMediaRouterService");
    try {
    mediaRouter = new MediaRouterService(context);
    ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
    } catch (Throwable e) {
    reportWtf("starting MediaRouterService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!disableTrustManager) {
    mSystemServiceManager.startService(TrustManagerService.class);
    }
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
    mSystemServiceManager.startService(FingerprintService.class);
    }
    traceBeginAndSlog("StartBackgroundDexOptService");
    try {
    BackgroundDexOptService.schedule(context);
    } catch (Throwable e) {
    reportWtf("starting BackgroundDexOptService", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
    mSystemServiceManager.startService(LauncherAppsService.class);
    }
    if (!disableNonCoreServices && !disableMediaProjection) {
    mSystemServiceManager.startService(MediaProjectionManagerService.class);
    }
    if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
    mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
    }
    final boolean safeMode = wm.detectSafeMode();
    if (safeMode) {
    mActivityManagerService.enterSafeMode();
    VMRuntime.getRuntime().disableJitCompilation();
    } else {
    VMRuntime.getRuntime().startJitCompilation();
    }
    mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady");
    try {
    vibrator.systemReady();
    } catch (Throwable e) {
    reportWtf("making Vibrator Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady");
    if (lockSettings != null) {
    try {
    lockSettings.systemReady();
    } catch (Throwable e) {
    reportWtf("making Lock Settings Service ready", e);
    }
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
    mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
    try {
    wm.systemReady();
    } catch (Throwable e) {
    reportWtf("making Window Manager Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (safeMode) {
    mActivityManagerService.showSafeModeOverlay();
    }
    Configuration config = wm.computeNewConfiguration();
    DisplayMetrics metrics = new DisplayMetrics();
    WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
    w.getDefaultDisplay().getMetrics(metrics);
    context.getResources().updateConfiguration(config, metrics);
    final Theme systemTheme = context.getTheme();
    if (systemTheme.getChangingConfigurations() != 0) {
    systemTheme.rebase();
    }
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePowerManagerServiceReady");
    try {
    mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    } catch (Throwable e) {
    reportWtf("making Power Manager Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePackageManagerServiceReady");
    try {
    mPackageManagerService.systemReady();
    } catch (Throwable e) {
    reportWtf("making Package Manager Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeDisplayManagerServiceReady");
    try {
    mDisplayManagerService.systemReady(safeMode, mOnlyCore);
    } catch (Throwable e) {
    reportWtf("making Display Manager Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    final NetworkManagementService networkManagementF = networkManagement;
    final NetworkStatsService networkStatsF = networkStats;
    final NetworkPolicyManagerService networkPolicyF = networkPolicy;
    final ConnectivityService connectivityF = connectivity;
    final NetworkScoreService networkScoreF = networkScore;
    final LocationManagerService locationF = location;
    final CountryDetectorService countryDetectorF = countryDetector;
    final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
    final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
    final AssetAtlasService atlasF = atlas;
    final InputManagerService inputManagerF = inputManager;
    final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
    final MediaRouterService mediaRouterF = mediaRouter;
    final MmsServiceBroker mmsServiceF = mmsService;
    mActivityManagerService.systemReady(new Runnable() {
    @Override
    public void run() {
    Slog.i(TAG, "Making services ready");
    mSystemServiceManager.startBootPhase(
    SystemService.PHASE_ACTIVITY_MANAGER_READY);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
    try {
    mActivityManagerService.startObservingNativeCrashes();
    } catch (Throwable e) {
    reportWtf("observing native crashes", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    if (!mOnlyCore) {
    Slog.i(TAG, "WebViewFactory preparation");
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
    mWebViewUpdateService.prepareWebViewInSystemServer();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI");
    try {
    startSystemUi(context);
    } catch (Throwable e) {
    reportWtf("starting System UI", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady");
    try {
    if (networkScoreF != null) networkScoreF.systemReady();
    } catch (Throwable e) {
    reportWtf("making Network Score Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady");
    try {
    if (networkManagementF != null) networkManagementF.systemReady();
    } catch (Throwable e) {
    reportWtf("making Network Managment Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady");
    try {
    if (networkStatsF != null) networkStatsF.systemReady();
    } catch (Throwable e) {
    reportWtf("making Network Stats Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady");
    try {
    if (networkPolicyF != null) networkPolicyF.systemReady();
    } catch (Throwable e) {
    reportWtf("making Network Policy Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady");
    try {
    if (connectivityF != null) connectivityF.systemReady();
    } catch (Throwable e) {
    reportWtf("making Connectivity Service ready", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Watchdog.getInstance().start();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart");
    mSystemServiceManager.startBootPhase(
    SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
    try {
    if (locationF != null) locationF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying Location Service running", e);
    }
    try {
    if (countryDetectorF != null) countryDetectorF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying CountryDetectorService running", e);
    }
    try {
    if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying NetworkTimeService running", e);
    }
    try {
    if (commonTimeMgmtServiceF != null) {
    commonTimeMgmtServiceF.systemRunning();
    }
    } catch (Throwable e) {
    reportWtf("Notifying CommonTimeManagementService running", e);
    }
    try {
    if (atlasF != null) atlasF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying AssetAtlasService running", e);
    }
    try {
    if (inputManagerF != null) inputManagerF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying InputManagerService running", e);
    }
    try {
    if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying TelephonyRegistry running", e);
    }
    try {
    if (mediaRouterF != null) mediaRouterF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying MediaRouterService running", e);
    }
    try {
    if (mmsServiceF != null) mmsServiceF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying MmsService running", e);
    }
    try {
    if (networkScoreF != null) networkScoreF.systemRunning();
    } catch (Throwable e) {
    reportWtf("Notifying NetworkScoreService running", e);
    }
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    });
    }

    startOtherServices()方法很长,看看就好。

  • ActivityManagerService的创建和初始化

    ActivityManagerService(AMS)是android系统中一个非常重要的服务,它主要管理四大组件和进程内存的调度,它在SystemServer里的创建和启动,主要调用了一下几个方法:

    • 1
      2
      mActivityManagerService = mSystemServiceManager.startService(
      ActivityManagerService.Lifecycle.class).getService();
    • 1
      mActivityManagerService.setSystemProcess();
    • 1
      mActivityManagerService.systemReady();

    变量mSystemServiceManager是一个SystemServiceManager类型的对象,首先调用它的startService()方法创建AMS对象,接着调用这个AMS对象的setSystemProcess()方法来初始化AMS中的一些重要工作,最后调用systemReady()方法来判断AM是否启动和初始化成功。在android系统中,很多的核心服务都会提供systemReady()方法来判断它相应的服务是否启动和初始化成功,因为有些核心服务如果没有启动或者初始化失败,会严重影响系统的使用,如AMS,WMS等核心服务。而有些服务没有提供这个方法,比如MountService,因为MountService主要管理Sdcard这部分,如果这个服务没有启动或者初始化失败,只会影响sdcard,对系统的影响不是很大。

    首先来看一下startService()方法创建AMS对象。

    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
    public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
    // 首先获得name为ActivityManagerService.Lifecycle
    final String name = serviceClass.getName();
    Slog.i(TAG, "Starting " + name);
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
    if (!SystemService.class.isAssignableFrom(serviceClass)) {
    throw new RuntimeException("Failed to create " + name
    + ": service must extend " + SystemService.class.getName());
    }
    final T service;
    try {
    Constructor<T> constructor = serviceClass.getConstructor(Context.class);
    // 通过构造方法的反射创建了一个实例,这里是Lifecycle对象
    service = constructor.newInstance(mContext);
    } catch (InstantiationException ex) {
    throw new RuntimeException("Failed to create service " + name
    + ": service could not be instantiated", ex);
    } catch (IllegalAccessException ex) {
    throw new RuntimeException("Failed to create service " + name
    + ": service must have a public constructor with a Context argument", ex);
    } catch (NoSuchMethodException ex) {
    throw new RuntimeException("Failed to create service " + name
    + ": service must have a public constructor with a Context argument", ex);
    } catch (InvocationTargetException ex) {
    throw new RuntimeException("Failed to create service " + name
    + ": service constructor threw an exception", ex);
    }
    mServices.add(service);
    try {
    service.onStart();
    } catch (RuntimeException ex) {
    throw new RuntimeException("Failed to start service " + name
    + ": onStart threw an exception", ex);
    }
    return service;
    } finally {
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
    }
    }

    SystemServiceManager类的startService()方法创建了一个Lifecycle实例,然后返回,而在SystemServer类里通过这个返回的实例调用getService()方法就获得AMS对象。Lifecycle是AMS的内部类,在创建这个实例的时候,会调用它的构造方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;
    public Lifecycle(Context context) {
    super(context);
    mService = new ActivityManagerService(context);
    }
    @Override
    public void onStart() {
    mService.start();
    }
    public ActivityManagerService getService() {
    return mService;
    }
    }

    Lifecycle的构造方法创建了一个AMS实例对象,而它的getService()方法会返回构造方法里创建的这个AMS实例对象。

    回到前面,接下来调用ActivityManagerService的setSystemProcess()方法。

    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
    public void setSystemProcess() {
    try {
    // 添加AMS到ServiceManager中
    ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
    ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
    ServiceManager.addService("meminfo", new MemBinder(this));
    ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
    ServiceManager.addService("dbinfo", new DbBinder(this));
    if (MONITOR_CPU_USAGE) {
    ServiceManager.addService("cpuinfo", new CpuBinder(this));
    }
    ServiceManager.addService("permission", new PermissionController(this));
    ServiceManager.addService("processinfo", new ProcessInfoService(this));
    ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
    mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
    synchronized (this) {
    ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
    app.persistent = true;
    app.pid = MY_PID;
    app.maxAdj = ProcessList.SYSTEM_ADJ;
    app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
    synchronized (mPidsSelfLocked) {
    mPidsSelfLocked.put(app.pid, app);
    }
    // 调整进程的调度优先级
    updateLruProcessLocked(app, false, null);
    // 调整OOM_Adj值
    updateOomAdjLocked();
    }
    } catch (PackageManager.NameNotFoundException e) {
    throw new RuntimeException(
    "Unable to find android system package", e);
    }
    }

    最后,继续调用ActivityManagerService的systemReady()方法。

    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
    public void systemReady(final Runnable goingCallback) {
    synchronized(this) {
    if (mSystemReady) {
    if (goingCallback != null) {
    goingCallback.run();
    }
    return;
    }
    mLocalDeviceIdleController
    = LocalServices.getService(DeviceIdleController.LocalService.class);
    mUserController.onSystemReady();
    mRecentTasks.onSystemReadyLocked();
    mAppOpsService.systemReady();
    mSystemReady = true;
    }
    // 从mPidsSelfLocked中找到那些优先于AMS启动的进程,即manifest里声明persistent为true的那些进程
    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
    for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
    ProcessRecord proc = mPidsSelfLocked.valueAt(i);
    if (!isAllowedWhileBooting(proc.info)){
    if (procsToKill == null) {
    procsToKill = new ArrayList<ProcessRecord>();
    }
    procsToKill.add(proc);
    }
    }
    }
    // 找到这些进程之后,通过removeProcessLocked()方法把它关闭
    synchronized(this) {
    if (procsToKill != null) {
    for (int i=procsToKill.size()-1; i>=0; i--) {
    ProcessRecord proc = procsToKill.get(i);
    Slog.i(TAG, "Removing system update proc: " + proc);
    removeProcessLocked(proc, true, false, "system update done");
    }
    }
    mProcessesReady = true;
    }
    Slog.i(TAG, "System now ready");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
    SystemClock.uptimeMillis());
    synchronized(this) {
    if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
    ResolveInfo ri = mContext.getPackageManager()
    .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
    STOCK_PM_FLAGS);
    CharSequence errorMsg = null;
    if (ri != null) {
    ActivityInfo ai = ri.activityInfo;
    ApplicationInfo app = ai.applicationInfo;
    if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
    mTopAction = Intent.ACTION_FACTORY_TEST;
    mTopData = null;
    mTopComponent = new ComponentName(app.packageName,
    ai.name);
    } else {
    errorMsg = mContext.getResources().getText(
    com.android.internal.R.string.factorytest_not_system);
    }
    } else {
    errorMsg = mContext.getResources().getText(
    com.android.internal.R.string.factorytest_no_action);
    }
    if (errorMsg != null) {
    mTopAction = null;
    mTopData = null;
    mTopComponent = null;
    Message msg = Message.obtain();
    msg.what = SHOW_FACTORY_ERROR_UI_MSG;
    msg.getData().putCharSequence("msg", errorMsg);
    mUiHandler.sendMessage(msg);
    }
    }
    }
    // 查询settings数据库,因为AMS会用到一些settings数据库里的数据
    retrieveSettings();
    final int currentUserId;
    synchronized (this) {
    currentUserId = mUserController.getCurrentUserIdLocked();
    readGrantedUriPermissionsLocked();
    }
    if (goingCallback != null) goingCallback.run();
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
    Integer.toString(currentUserId), currentUserId);
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
    Integer.toString(currentUserId), currentUserId);
    mSystemServiceManager.startUser(currentUserId);
    synchronized (this) {
    startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
    mBooting = true;
    if (UserManager.isSplitSystemUser()) {
    ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
    try {
    AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
    UserHandle.USER_SYSTEM);
    } catch (RemoteException e) {
    throw e.rethrowAsRuntimeException();
    }
    }
    // 启动Launcher
    startHomeActivityLocked(currentUserId, "systemReady");
    try {
    if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
    Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
    + " data partition or your device will be unstable.");
    mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
    }
    } catch (RemoteException e) {
    }
    if (!Build.isBuildConsistent()) {
    Slog.e(TAG, "Build fingerprint is not consistent, warning user");
    mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
    }
    long ident = Binder.clearCallingIdentity();
    try {
    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
    | Intent.FLAG_RECEIVER_FOREGROUND);
    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
    broadcastIntentLocked(null, null, intent,
    null, null, 0, null, null, null, AppOpsManager.OP_NONE,
    null, false, false, MY_PID, Process.SYSTEM_UID,
    currentUserId);
    intent = new Intent(Intent.ACTION_USER_STARTING);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
    broadcastIntentLocked(null, null, intent,
    null, new IIntentReceiver.Stub() {
    @Override
    public void performReceive(Intent intent, int resultCode, String data,
    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
    throws RemoteException {
    }
    }, 0, null, null,
    new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
    null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
    } catch (Throwable t) {
    Slog.wtf(TAG, "Failed sending first user broadcasts", t);
    } finally {
    Binder.restoreCallingIdentity(ident);
    }
    mStackSupervisor.resumeFocusedStackTopActivityLocked();
    mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
    }
    }

    至此,ActivityManagerService的创建和它的核心方法的调用分析完毕。