系统启动流程分析之SystemServiceManager阶段管理总结

820 阅读2分钟

「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」。

SystemServiceManager阶段管理总结

在SystemServer启动过程中,创建了一系列的服务,其中的一个重要的类就是SystemServiceManager(后续全部使用SSM来代替),其控制了SystemServer启动过程中的各个阶段,管理各个服务在各个阶段的初始化和相应资源的加载,那么SSM是如何做到的呢?

SystemServiceManager的startService函数流程分析一文中,曾经有说明过,当SystemServiceManager的startService函数被调用时,会完成三个任务:

  1. 初始化对应的SystemService,并且调用其以Context对象为参数的单参构造函数,而传递的参数是在SystemServer中通过createSystemContext创建的Context对象
  2. 将传入参数SystemService对象添加到SSM.mServices中保存,mServices是一个SystemService对象组成的ArrayList对象
  3. 调用传入参数SystemService对象的onStart函数

此前的分析中,服务启动的过程中,我们只说明了第一和第三个步骤,那么第二个步骤,将所有的服务注册到SSM.mServices中后,具体是怎么使用这些服务的呢?

代码分析

通读SystemServer的代码后发现,SSM在SystemServer的各个阶段都会调用startBootPhase,然后传入不同的参数

SystemServer.java
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    // ......
}

private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
}

ActivityManagerService.java
final void finishBooting() {
    // ......
    mSystemServiceManager.startBootPhase(t, SystemService.PHASE_BOOT_COMPLETED);
    // ......
}

从上述的代码中可以看到,此处在SystemServer进程初始化的各个阶段,会调用SSM对象的startBootPhase函数,只是参数不同,那么这个函数中究竟做了些什么呢?

/**
 * Starts the specified boot phase for all system services that have been started up to
 * this point.
 *
 * @param t trace logger
 * @param phase The boot phase to start.
 */
public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
    // 结合后一句语句的赋值,此处表明,调用startBootPhase函数时,每调用一次的后一次参数必须比前一次参数的值大
    // 这样保证不会出现重复调用
    if (phase <= mCurrentPhase) {
        throw new IllegalArgumentException("Next phase must be larger than previous");
    }
    mCurrentPhase = phase;

    Slog.i(TAG, "Starting phase " + mCurrentPhase);
    try {
        t.traceBegin("OnBootPhase_" + phase);
        // 获取此前加入到mServices中的所有系统服务,然后一一调用其onBootPhase函数
        final int serviceLen = mServices.size();
        for (int i = 0; i < serviceLen; i++) {
            final SystemService service = mServices.get(i);
            long time = SystemClock.elapsedRealtime();
            t.traceBegin("OnBootPhase_" + phase + "_" + service.getClass().getName());
            try {
                service.onBootPhase(mCurrentPhase);
            }
            // ...... catch代码,此处省略
        }
    } finally {
        t.traceEnd();
    }

    // 当系统启动完成后,此处会直接结束SystemServerInitThreadPool线程池
    if (phase == SystemService.PHASE_BOOT_COMPLETED) {
        final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
        t.logDuration("TotalBootTime", totalBootTime);
        SystemServerInitThreadPool.shutdown();
    }
}

哦哦,原来此处是通过调用不同的阶段数值来控制系统服务的不同阶段的初始化工作的

阶段启动的系统服务汇总

SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY
    --> UriGrantsManagerService.Lifecycle.onBootPhase
    --> DisplayManagerService.onBootPhase
SystemService.PHASE_LOCK_SETTINGS_READY
    --> ContentService.Lifecycle
    --> MultiClientInputMethodManagerService.Lifecycle
    --> DevicePolicyManagerService.Lifecycle
    --> WallpaperManagerService.Lifecycle
    --> ShortcutService.Lifecycle
SystemService.PHASE_SYSTEM_SERVICES_READY
    --> UriGrantsManagerService.Lifecycle.onBootPhase
    --> ActivityManagerService.Lifecycle.onBootPhase
    --> RecoverySystemService.Lifecycle.onBootPhase
    --> UsageStatsService.
    --> CachedDeviceStateService
    --> BinderCallsStatsService.LifeCycle
    --> LooperStatsService.Lifecycle
    --> ContentService.Lifecycle
    --> DropBoxManagerService
    --> AlarmManagerService
    --> VrManagerService
    --> BluetoothService
    --> IpConnectivityMetrics
    --> PinnerService
    --> MultiClientInputMethodManagerService.Lifecycle
    --> AccessibilityManagerService.Lifecycle
    --> StorageManagerService.Lifecycle
    --> UiModeManagerService
    --> PersistentDataBlockService
    --> TestHarnessModeService
    --> DeviceIdleController
    --> DevicePolicyManagerService.Lifecycle
    --> NetworkScoreService.Lifecycle
    --> WifiService
    --> WifiScanningService
    --> RttService
    --> WifiAwareService
    --> WifiP2pService
    --> EthernetService
    --> NotificationManagerService
    --> LocationManagerService.Lifecycle
    --> WallpaperManagerService.Lifecycle
    --> JobSchedulerService
    --> TrustManagerService
    --> VoiceInteractionManagerService
    --> ContextHubSystemService
    --> HdmiControlService
    --> TvInputManagerService
    --> PeopleService
    --> StatsPullAtomService
    --> AttentionManagerService
SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY
    --> ContentService.Lifecycle
    --> MultiClientInputMethodManagerService.Lifecycle
    --> DevicePolicyManagerService.Lifecycle
    --> WallpaperManagerService.Lifecycle
    --> SoundTriggerService
SystemService.PHASE_ACTIVITY_MANAGER_READY
    --> ActivityManagerService.Lifecycle.onBootPhase
    --> ThermalManagerService.onBootPhase
    --> UserManagerService.LifeCycle.
    --> BatteryService
    --> TelecomLoaderService
    --> ContentService.Lifecycle
    --> BluetoothService
    --> NetworkWatchlistService.Lifecycle
    --> MultiClientInputMethodManagerService.Lifecycle
    --> InputMethodManagerService.Lifecycle
    --> StorageManagerService.Lifecycle
    --> LockSettingsService.Lifecycle
    --> DevicePolicyManagerService.Lifecycle
    --> NotificationManagerService
    --> WallpaperManagerService.Lifecycle
    --> AudioService.Lifecycle
    --> DockObserver
    --> AdbService.Lifecycle
    --> UsbService.Lifecycle
    --> AppWidgetService
    --> BlobStoreManagerService
    --> SliceManagerService.Lifecycle
    --> AppBindingService.Lifecycle
    --> PermissionPolicyService
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START
    --> ActivityManagerService.Lifecycle.onBootPhase
    --> PowerManagerService.onBootPhase
    --> ContentService.Lifecycle
    --> MultiClientInputMethodManagerService.Lifecycle
    --> DevicePolicyManagerService.Lifecycle
    --> NotificationManagerService
    --> LocationManagerService.Lifecycle
    --> WallpaperManagerService.Lifecycle
    --> JobSchedulerService
    --> SoundTriggerService
    --> TrustManagerService
    --> VoiceInteractionManagerService
    --> GestureLauncherService
    --> SensorNotificationService
    --> EmergencyAffordanceService
    --> DreamManagerService
    --> TvInputManagerService
    --> TvRemoteService
    --> StatsCompanion.Lifecycle
    --> StatsPullAtomService
    --> AppBindingService.Lifecycle
    --> CarServiceHelperService
SystemService.PHASE_BOOT_COMPLETED
    --> PowerManagerService.onBootPhase
    --> RollbackManagerService
    --> GpuService
    --> ContentService.Lifecycle
    --> DropBoxManagerService
    --> IorapForwardingService
    --> MultiClientInputMethodManagerService.Lifecycle
    --> StorageManagerService.Lifecycle
    --> TestHarnessModeService
    --> DevicePolicyManagerService.Lifecycle
    --> NetworkScoreService.Lifecycle
    --> WifiService
    --> WallpaperManagerService.Lifecycle
    --> AdbService.Lifecycle
    --> UsbService.Lifecycle
    --> TwilightService
    --> ColorDisplayService
    --> TrustManagerService
    --> SensorNotificationService
    --> BlobStoreManagerService
    --> HdmiControlService
    --> ShortcutService.Lifecycle
    --> StatsCompanion.Lifecycle
    --> IncidentCompanionService
    --> CarServiceHelperService