Android SystemServer启动(二)

903 阅读5分钟

Android init 启动

Android Linux Zygote启动

Android Java Zygote启动

Android SystemServer启动(一)

继续上篇文章的SystemServer启动分析。

此次分析过程基于Android 10.0

run

在之前已经分析到,通过SystemServerrun方法进入到SystemServer内部逻辑。

所以我们直接来看run方法

private void run() {
    try {
        traceBeginAndSlog("InitBeforeStartServices");
        ...
        ...
        
        // 创建Looper
        Looper.prepareMainLooper();
        Looper.getMainLooper().setSlowLogThresholdMs(
                SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);

        // 初始化native service
        System.loadLibrary("android_servers");

        performPendingShutdown();

        // 创建system context
        createSystemContext();

        // 创建SystemServiceManager
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setStartInfo(mRuntimeRestart,
                mRuntimeStartElapsedTime, mRuntimeStartUptime);
        
        // 添加到本地LocalServices中,以便后续获取对应的服务对象
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        SystemServerInitThreadPool.get();
    } finally {
        traceEnd();  // InitBeforeStartServices
    }

    // 启动各项services
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        traceEnd();
    }

    StrictMode.initVmDefaults(null);

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

    // 开启loop循环,等待消息的来临
    Looper.loop();
    throw new RuntimeException("Main thread loop unexpectedly exited");
}

SystemServerrun方法中主要做的事情是:

  1. 创建当前线程的Looper
  2. 加载native services原生库android_servers
  3. 创建SystemContext,通过ActivityThread来获取SystemContext
  4. 创建SystemServiceManager,用来启动后续的各项服务
  5. 开启各项服务
  6. 开启Looper循环,等待消息的来临并执行

SystemContext

其中SystemContext的创建是通过ActivityThread来获取的

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

最终获取到的SystemContext是由ContextImpl创建的

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}

SystemServiceManager

它是SystemServer的服务大管家,提供启动服务的相关方法。

主要涉及的方法有

  1. startService: 通过反射创建相关服务,并且调用对应服务的onStart()方法来开启服务
  2. startBootPhase: 开启特殊的启动阶段节点,各项服务会根据不同的阶段节点执行不同的逻辑。

启动的阶段节点分别为:

// 启动阶段,初始化一些默认展示
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;

// 该启动阶段将会锁定setting数据
public static final int PHASE_LOCK_SETTINGS_READY = 480;

// 该启动阶段将会调用核心的system services,例如PowerManager与PackageManager
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

// 该启动阶段将会调用设备特殊服务
public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

// 该启动阶段将会将会发送服务广播
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

// 该启动阶段将会启动不绑定三方app
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

// 该启动阶段标志着启动完成,用户可以进行设备交互,应用桌面已经启动
public static final int PHASE_BOOT_COMPLETED = 1000;

这些启动阶段会穿插在各项的服务启动序列中,每一个启动阶段节点的插入,都会伴随着该启动阶段节点之前的服务执行相关逻辑。

所以这里启动阶段节点相对于标识或者说依赖关系,即后续的启动阶段需要依赖于前面某些服务的特色处理逻辑之后才能进行。

而这些启动阶段的节点体现都分布在这些方法中

traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();

具体的节点插入时机为

private void startBootstrapServices() {
        mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
}

private void startCoreServices() {
        ...
}

private void startOtherServices() {
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);

        mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);

        mActivityManagerService.systemReady(() -> {
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);        
            
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
        }
}

对应的响应各个阶段的处理逻辑是在对应serviceonBootPhase()方法中

public void onBootPhase(int phase) {
	...
}

下面我们来看下各个阶段都启动了哪些服务。

startBootstrapServices

private void startBootstrapServices() {
    final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
    traceBeginAndSlog(TAG_SYSTEM_CONFIG);
    SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
    traceEnd();

    // 启动Installer
    Installer installer = mSystemServiceManager.startService(Installer.class);

    // 启动DeviceIdentifiersPolicyService
    mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

    // 启动ActivityManagerService
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);

    // 启动PowerManagerService
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

    // 初始化PowerManager
    mActivityManagerService.initPowerManagement();

    // 启动RecoverySystemService
    mSystemServiceManager.startService(RecoverySystemService.class);

    RescueParty.noteBoot(mSystemContext);

    // 启动LightsService
    mSystemServiceManager.startService(LightsService.class);

    // 启动SidekickService
    if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
        mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
    }

    // 启动DisplayManagerService
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);

    // 插入启动阶段节点,执行对应的节点逻辑
    mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
    
    ...
    ...
}

在开始插入启动阶段节点之前,也可以称之为BootPhase 0,启动的服务有:

Installer
DeviceIdentifiersPolicyService
UriGrantsManagerService
ActivityManagerService
PowerManagerService
RecoverySystemService
LightsService
DisplayManagerService

由于PackageManager启动需要DisplayManagerService的相关信息,所以设置BootPhase 100,执行DisplayManagerService中的onBootPhase方法来处理BootPhase 100的逻辑

public void onBootPhase(int phase) {
    if (phase == PHASE_WAIT_FOR_DEFAULT_DISPLAY) {
        synchronized (mSyncRoot) {
            long timeout = SystemClock.uptimeMillis()
                    + mInjector.getDefaultDisplayDelayTimeout();
            while (mLogicalDisplays.get(Display.DEFAULT_DISPLAY) == null ||
                    mVirtualDisplayAdapter == null) {
                long delay = timeout - SystemClock.uptimeMillis();
                if (delay <= 0) {
                    throw new RuntimeException("Timeout waiting for default display "
                            + "to be initialized. DefaultDisplay="
                            + mLogicalDisplays.get(Display.DEFAULT_DISPLAY)
                            + ", mVirtualDisplayAdapter=" + mVirtualDisplayAdapter);
                }
                if (DEBUG) {
                    Slog.d(TAG, "waitForDefaultDisplay: waiting, timeout=" + delay);
                }
                try {
                    mSyncRoot.wait(delay);
                } catch (InterruptedException ex) {
                }
            }
        }
    }
}

处理完之后继续启动PackageManagerService与其他的服务。

BootPhase 100BootPhase 480会启动大量的服务。

包括初始化的服务、核心服务与其他服务。分别从startBootstrapServicesstartCoreServicesstartOtherServices

private void startBootstrapServices() {
    ...
    ...

    // BootPhase 100

    // 启动PackageManagerService
    try {
        Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
                mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }
    mFirstBoot = mPackageManagerService.isFirstBoot();
    mPackageManager = mSystemContext.getPackageManager();

    // 启动UserManagerService,创建/data/user/ 目录
    mSystemServiceManager.startService(UserManagerService.LifeCycle.class);

    // 设置AMS
    mActivityManagerService.setSystemProcess();

    // 启动OverlayManagerService
    mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));

    // 启动SensorPrivacyService,传感器
    mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));

    ...
}

BootPhase 100阶段,startBootstrapServices启动以下服务

PackageManagerService
UserManagerService
OverlayManagerService
SensorPrivacyService

随后进入startCoreServices

startCoreServices

private void startCoreServices() {
    // 启动BatterService, 管理电量,需要LightService
    mSystemServiceManager.startService(BatteryService.class);

    // 启动UsageStatsService,统计应用使用情况
    mSystemServiceManager.startService(UsageStatsService.class);
    mActivityManagerService.setUsageStatsManager(
            LocalServices.getService(UsageStatsManagerInternal.class));

    // 启动WebViewUpdateService, 管理WebView更新
    if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
        mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
    }

    // 启动CachedDeviceStateService, 缓存设备状态
    mSystemServiceManager.startService(CachedDeviceStateService.class);

    // 启动BinderCallsStatsService, 记录cpu在binder回调中花费的时间
    mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);

    // 启动LooperStatsService, 记录使用handler message花费的时间
    mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);

    // 启动RollbackManagerService,管理apk回卷
    mSystemServiceManager.startService(RollbackManagerService.class);

    // 启动BugreportManagerService, 捕获bug的报告
    mSystemServiceManager.startService(BugreportManagerService.class);

    // 启动GpuService, 管理GPU
    mSystemServiceManager.startService(GpuService.class);

}

// BootPhase 100 启动的服务
UsageStatsService
WebViewUpdateService
CachedDeviceStateService
BinderCallsStatsService
LooperStatsService
RollbackManagerService
BugreportManagerService
GpuService

以上是启动的核心服务;继续进入startOtherServices

startOtherServices

    private void startOtherServices() {
        final Context context = mSystemContext; // 获取Context

        try {

            ServiceManager.addService("sec_key_att_app_id_provider",
                    new KeyAttestationApplicationIdProviderService(context));

            mSystemServiceManager.startService(KeyChainSystemService.class);

            ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());

            mSystemServiceManager.startService(TelecomLoaderService.class);

            telephonyRegistry = new TelephonyRegistry(context);
            ServiceManager.addService("telephony.registry", telephonyRegistry);

            mEntropyMixer = new EntropyMixer(context);

            mContentResolver = context.getContentResolver(); // 获取ContentResolver

            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);

            mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);

            mActivityManagerService.installSystemProviders(); // 安装系统Provider

            ...

            mSystemServiceManager.startService(new AlarmManagerService(context)); // 闹钟服务

            ...

            mActivityManagerService.setWindowManager(wm); // 设置WindowManager

            ...

        }

        ...

        // 进入安全模式
        if (safeMode) {
            mActivityManagerService.enterSafeMode();
        }

        ...
        ...

        // BootPhase  480
        mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);

        // BootPhase 500
        mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);


        // BootPhase 520
        mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);

        try {
            wm.systemReady();
        } catch (Throwable e) {
            reportWtf("making Window Manager Service ready", e);
        }

        if (safeMode) {
            mActivityManagerService.showSafeModeOverlay();
        }

        // 更新Configuration
        final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
        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();
        }

        try {
            mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
        } catch (Throwable e) {
            reportWtf("making Power Manager Service ready", e);
        }

        mSystemServiceManager.startService(PermissionPolicyService.class);

        mPackageManagerService.systemReady();

        ...

        mActivityManagerService.systemReady(() -> {
            
            // BootPhase 550
            mSystemServiceManager.startBootPhase(
                    SystemService.PHASE_ACTIVITY_MANAGER_READY);

            try {
                mActivityManagerService.startObservingNativeCrashes();
            } catch (Throwable e) {
                reportWtf("observing native crashes", e);
            }

            traceBeginAndSlog("MakeConnectivityServiceReady");
            try {
                if (connectivityF != null) {
                    connectivityF.systemReady();
                }
            } catch (Throwable e) {
                reportWtf("making Connectivity Service ready", e);
            }

            ...
            
            // BootPhase 600
            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);
            }

            ...

        }, BOOT_TIMINGS_TRACE_LOG);

    }

startOtherServices中启动了大量服务,总共差不多有80多种,这里就不一一列举出来。

我这里将其与BootPhase做了个归总,来看一下各个启动阶段节点都启动了哪些服务与对应服务的操作。

// BootPhase 100
KeyAttestationApplicationIdProviderService (startOtherServices)
KeyChainSystemService 
SchedulingPolicyService
TelecomLoaderService
TelephonyRegistry
EntropyMixer
AccountManagerService
ContentService

...(大量服务)

AppBindingService

BootPhase 480

BootPhase 500

PermissionPolicyService
DeviceSpecificServices(包含大量Service)

// 准备好 Power、Package与Diaplay服务
PowerManagerService.systemReady
PackageManagerService.systemReady
DisplayManagerService.systemReady

BootPhase 520

BootPhase 550

CarServiceHelperService
startSystemUi

// 准备好 Network、Ip、Connectivity服务
NetworkManagementService.systemReady
NetworkPolicyManagerService.systemReady
IpSecService.systemReady
NetworkStatsService.systemReady
ConnectivityService.systemReady
NetworkPolicyService.systemReady


BootPhase 600
 
NetworkStack

// 运行Location、CountryDetection、Network、Input、Telephoney、Media、Mms、Incident服务
LocationService.systemRunning
CountryDetectionService.systemRunning
NetworkTimeUpdateService.systemRunning
InputManagerService.systemRunning
TelephonyRegistry.systemRunning
MediaRouterService.systemRunning
MmsServiceBroker.systemRunning
IncidentDaemon.systemRunning

最后经过以上一系列的服务调用,会调用ActivityManagerServicefinishBooting方法来执行最后一个BootPhase 1000

final void finishBooting() {
    ...

    // BootPhase 1000
    mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);

    ...
}

至此,系统服务启动阶段完成就绪,system_server进程启动完成则进入Looper.loop()状态,等待消息队列MessageQueue中的消息到来,然后执行对应的Message

以上是SystemService的启动过程,主要通过BootPhase 0 ~ BootPhase 1000来分别启动不同的Service,根据不同的BootPhase,相应的Service执行不同的逻辑。后续Service启动逻辑与执行逻辑可能依赖于之前的Service,而它们之间的依赖管理是通过BootPhase来建立的。

微信公众号:Android补给站,专注于Android进阶、算法与面试分析,还有不定期福利

推荐

android_startup: 提供一种在应用启动时能够更加简单、高效的方式来初始化组件。开发人员可以使用android-startup来简化启动序列,并显式地设置初始化顺序与组件之间的依赖关系。 与此同时android-startup支持同步与异步等待,并通过有向无环图拓扑排序的方式来保证内部依赖组件的初始化顺序。

AwesomeGithub: 基于Github客户端,纯练习项目,支持组件化开发,支持账户密码与认证登陆。使用Kotlin语言进行开发,项目架构是基于Jetpack&DataBindingMVVM;项目中使用了ArouterRetrofitCoroutineGlideDaggerHilt等流行开源技术。

flutter_github: 基于Flutter的跨平台版本Github客户端,与AwesomeGithub相对应。

android-api-analysis: 结合详细的Demo来全面解析Android相关的知识点, 帮助读者能够更快的掌握与理解所阐述的要点。

daily_algorithm: 算法进阶汇总,由浅入深,欢迎加入一起共勉。