当前位置:   article > 正文

Android SystemServer 启动流程分析

systemservicemanager.class

56ef2c3074687a2ad50bc5439efd3042.gif

和你一起终身学习,这里是程序员Android

经典好文推荐,通过阅读本文,您将收获以下知识点:

一、SystemServer 启动的服务有哪些
二、SystemServer启动总体流程概述
三、SystemServer 如何启动,是谁启动的?
四、 SystemServer 启动入门 main 方法
五、SystemServer Run 方法初始与启动
六、SystemServer 的引导服务有哪些
七、SystemServer 的核心服务有哪些
八、SystemServer 的其他服务有哪些

一、SystemServer 启动的服务有哪些

SystemServer 主要启动 ActivityManagerServicePackageManagerServiceWindowManagerServiceLightsServiceLightsServiceBatteryServiceTelephonyRegistryRecoverySystemService 等等,主要分三大类,后文会详细列举。

1.SystemServer 启动的服务

8f0e40d74a34242c6e903bda79e747b6.jpeg

SystemServer 启动的服务

82ae9a630d965309141d50845b22b743.jpeg

SystemServer 启动的服务

二、SystemServer启动总体流程概述

1.SystemServer 代码

\alps\frameworks\base\services\java\com\android\server\SystemServer.java

0ca6220abb88ac469f3b31a69bd911cb.jpeg

SystemServer 进程启动导图

三、SystemServer 如何启动,是谁启动的?

SystemServer是通过Zygote 启动的,在ZygoteInit.java类的(frameworks\base\core\java\com\android\internal\os\ZygoteInit.java) main方法中通过forkSystemServer启动。

  1. public static void main(String argv[]) {
  2. ....
  3. //设置变量区分是否启动SystemServer
  4. boolean startSystemServer = false;
  5. String socketName = "zygote";
  6. String abiList = null;
  7. boolean enableLazyPreload = false;
  8. for (int i = 1; i < argv.length; i++) {
  9. if ("start-system-server".equals(argv[i])) {
  10. // 需要启动时候,将标志位设置为true
  11. startSystemServer = true;
  12. } else if ("--enable-lazy-preload".equals(argv[i])) {
  13. enableLazyPreload = true;
  14. }
  15. ... ...
  16. if (startSystemServer) {
  17. // 通过 Zygote fork 出 SystemServer
  18. Runnable r = forkSystemServer(abiList, socketName, zygoteServer);
  19. // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
  20. // child (system_server) process.
  21. if (r != null) {
  22. r.run();
  23. return;
  24. }
  25. }

四、 SystemServer 启动入门 main 方法

main 入口 通过 new SystemServer().run();开启SystemServer启动。

main 入口代码如下:

  1. /**
  2. * The main entry point from zygote.
  3. */
  4. public static void main(String[] args) {
  5. new SystemServer().run();
  6. }

通过Main入口,调用SystemServer 构造方法。

  1. public SystemServer() {
  2. // 检查工程模式.
  3. mFactoryTestMode = FactoryTest.getMode();
  4. // 判断是否是重启
  5. mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
  6. mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
  7. mRuntimeStartUptime = SystemClock.uptimeMillis();
  8. }
  9. private void run() {
  10. ... ...
  11. }

五、SystemServer Run 方法初始与启动

1.SystemServer Run 方法

  1. private void run() {
  2. try {
  3. traceBeginAndSlog("InitBeforeStartServices");
  4. //初始化时间
  5. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  6. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  7. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  8. }
  9. //设置默认时区
  10. String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  11. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  12. Slog.w(TAG, "Timezone not set; setting to GMT.");
  13. SystemProperties.set("persist.sys.timezone", "GMT");
  14. }
  15. ... ...
  16. // 开始进入Android SystemServer
  17. Slog.i(TAG, "Entered the Android system server!");
  18. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  19. EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
  20. if (!mRuntimeRestart) {
  21. MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
  22. }
  23. ... ...
  24. //如果支持指纹,需初始化指纹ro.build.fingerprint
  25. Build.ensureFingerprintProperty();
  26. ... ...
  27. // 初始化 native services.
  28. System.loadLibrary("android_servers");
  29. // 检查最近一次关机是否失败
  30. performPendingShutdown();
  31. // 初始化 the system context.
  32. createSystemContext();
  33. // 创建 system service manager.
  34. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  35. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  36. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  37. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  38. // 初始化SystemServer 线程池
  39. SystemServerInitThreadPool.get();
  40. } finally {
  41. traceEnd(); // InitBeforeStartServices
  42. }
  43. ... ...
  44. // 开始启动 services.
  45. try {
  46. traceBeginAndSlog("StartServices");
  47. // 1. 启动引导服务 详见分析六
  48. startBootstrapServices();
  49. // 2. 启动核心服务 详见分析七
  50. startCoreServices();
  51. // 3.启动其他服务 详见分析八
  52. startOtherServices();
  53. SystemServerInitThreadPool.shutdown();
  54. } catch (Throwable ex) {
  55. Slog.e("System", "******************************************");
  56. Slog.e("System", "************ Failure starting system services", ex);
  57. throw ex;
  58. } finally {
  59. traceEnd();
  60. }
  61. StrictMode.initVmDefaults(null);
  62. }

六、SystemServer 的引导服务有哪些

SystemServer启动的常用引导服务有installed 、DeviceIdentifiersPolicyService、 ActivityManagerService.、PowerManagerService 、 RecoverySystemService 、 LightsService 、 PackageManagerService、UserManagerService、OverlayManagerService等。

275c125847cd7c472fa45ce94cb57cdf.jpeg

启动的引导服务的大致流程

1.startBootstrapServices代码

  1. /**
  2. * Starts the small tangle of critical services that are needed to get
  3. * the system off the ground. These services have complex mutual dependencies
  4. * which is why we initialize them all in one place here. Unless your service
  5. * is also entwined in these dependencies, it should be initialized in one of
  6. * the other functions.
  7. */
  8. private void startBootstrapServices() {
  9. Slog.i(TAG, "Reading configuration...");
  10. final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
  11. traceBeginAndSlog(TAG_SYSTEM_CONFIG);
  12. SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
  13. traceEnd();
  14. // 启动 installed
  15. traceBeginAndSlog("StartInstaller");
  16. Installer installer = mSystemServiceManager.startService(Installer.class);
  17. traceEnd();
  18. //启动 设备标识符 服务
  19. traceBeginAndSlog("DeviceIdentifiersPolicyService");
  20. mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
  21. traceEnd();
  22. // 启动 AMS.
  23. traceBeginAndSlog("StartActivityManager");
  24. mActivityManagerService = mSystemServiceManager.startService(
  25. ActivityManagerService.Lifecycle.class).getService();
  26. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  27. mActivityManagerService.setInstaller(installer);
  28. traceEnd();
  29. //启动 PMS
  30. traceBeginAndSlog("StartPowerManager");
  31. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
  32. traceEnd();
  33. //初始化电源管理功能
  34. traceBeginAndSlog("InitPowerManagement");
  35. mActivityManagerService.initPowerManagement();
  36. traceEnd();
  37. // 启动 RecoverySystemService
  38. traceBeginAndSlog("StartRecoverySystemService");
  39. mSystemServiceManager.startService(RecoverySystemService.class);
  40. traceEnd();
  41. // 为启动事件添加记录
  42. RescueParty.noteBoot(mSystemContext);
  43. // 启动 LightsService 管理LEDs 和背光显示
  44. traceBeginAndSlog("StartLightsService");
  45. mSystemServiceManager.startService(LightsService.class);
  46. traceEnd();
  47. traceBeginAndSlog("StartSidekickService");
  48. // Package manager isn't started yet; need to use SysProp not hardware feature
  49. if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
  50. mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
  51. }
  52. traceEnd();
  53. // Display manager is needed to provide display metrics before package manager
  54. // starts up.
  55. traceBeginAndSlog("StartDisplayManager");
  56. mDisplayManagerService = mSystemServiceManager.startService(LightsService.class);
  57. traceEnd();
  58. // We need the default display before we can initialize the package manager.
  59. traceBeginAndSlog("WaitForDisplay");
  60. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  61. traceEnd();
  62. // Only run "core" apps if we're encrypting the device.
  63. String cryptState = SystemProperties.get("vold.decrypt");
  64. if (ENCRYPTING_STATE.equals(cryptState)) {
  65. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  66. mOnlyCore = true;
  67. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  68. Slog.w(TAG, "Device encrypted - only parsing core apps");
  69. mOnlyCore = true;
  70. }
  71. // 启动 PackageManagerService
  72. if (!mRuntimeRestart) {
  73. MetricsLogger.histogram(null, "boot_package_manager_init_start",
  74. (int) SystemClock.elapsedRealtime());
  75. }
  76. traceBeginAndSlog("StartPackageManagerService");
  77. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  78. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  79. mFirstBoot = mPackageManagerService.isFirstBoot();
  80. mPackageManager = mSystemContext.getPackageManager();
  81. traceEnd();
  82. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  83. MetricsLogger.histogram(null, "boot_package_manager_init_ready",
  84. (int) SystemClock.elapsedRealtime());
  85. }
  86. // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
  87. // A/B artifacts after boot, before anything else might touch/need them.
  88. // Note: this isn't needed during decryption (we don't have /data anyways).
  89. if (!mOnlyCore) {
  90. boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
  91. false);
  92. if (!disableOtaDexopt) {
  93. traceBeginAndSlog("StartOtaDexOptService");
  94. try {
  95. OtaDexoptService.main(mSystemContext, mPackageManagerService);
  96. } catch (Throwable e) {
  97. reportWtf("starting OtaDexOptService", e);
  98. } finally {
  99. traceEnd();
  100. }
  101. }
  102. }
  103. //启动多用户 UserManagerService
  104. traceBeginAndSlog("StartUserManagerService");
  105. mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
  106. traceEnd();
  107. // 初始化属性缓存
  108. traceBeginAndSlog("InitAttributerCache");
  109. AttributeCache.init(mSystemContext);
  110. traceEnd();
  111. // Set up the Application instance for the system process and get started.
  112. traceBeginAndSlog("SetSystemProcess");
  113. mActivityManagerService.setSystemProcess();
  114. traceEnd();
  115. // DisplayManagerService needs to setup android.display scheduling related policies
  116. // since setSystemProcess() would have overridden policies due to setProcessGroup
  117. mDisplayManagerService.setupSchedulerPolicies();
  118. /// M: CTA requirement - permission control @{
  119. /*
  120. * M: MOTA for CTA permissions handling
  121. * This function is used for granting CTA permissions after OTA upgrade.
  122. * This should be placed after AMS is added to ServiceManager and before
  123. * starting other services since granting permissions needs AMS instance
  124. * to do permission checking.
  125. */
  126. mPackageManagerService.onAmsAddedtoServiceMgr();
  127. /// @}
  128. // 启动 OverlayManagerService
  129. traceBeginAndSlog("StartOverlayManagerService");
  130. mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
  131. traceEnd();
  132. // The sensor service needs access to package manager service, app ops
  133. // service, and permissions service, therefore we start it after them.
  134. // Start sensor service in a separate thread. Completion should be checked
  135. // before using it.
  136. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
  137. TimingsTraceLog traceLog = new TimingsTraceLog(
  138. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  139. traceLog.traceBegin(START_SENSOR_SERVICE);
  140. startSensorService();
  141. traceLog.traceEnd();
  142. }, START_SENSOR_SERVICE);
  143. }

七、SystemServer 的核心服务有哪些

1.SystemServer 核心服务

有 BatteryService 、UsageStatsService、WebViewUpdateService、BinderCallsStatsService4种核心服务。

d6c43282bcf73fe4777c544b55f9237c.jpeg

SystemServer 4种核心服务

2.startCoreServices 代码

  1. /**
  2. * Starts some essential services that are not tangled up in the bootstrap process.
  3. */
  4. private void startCoreServices() {
  5. // 启动 BatteryService 管理电池服务(电压、电量、温度)
  6. traceBeginAndSlog("StartBatteryService");
  7. // Tracks the battery level. Requires LightService.
  8. mSystemServiceManager.startService(BatteryService.class);
  9. traceEnd();
  10. // 启动 UsageStatsService 收集应用持久化数据的服务
  11. traceBeginAndSlog("StartUsageService");
  12. mSystemServiceManager.startService(UsageStatsService.class);
  13. mActivityManagerService.setUsageStatsManager(
  14. LocalServices.getService(UsageStatsManagerInternal.class));
  15. traceEnd();
  16. // 启动 WebViewUpdateService 监视 WebView 是否更新
  17. if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
  18. traceBeginAndSlog("StartWebViewUpdateService");
  19. mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
  20. traceEnd();
  21. }
  22. //启动 CPU Binder 调度服务
  23. traceBeginAndSlog("StartBinderCallsStatsService");
  24. BinderCallsStatsService.start();
  25. traceEnd();
  26. }

八、SystemServer 的其他服务有哪些

1.startOtherServices 启动的服务主要有:

KeyChainSystemService、TelecomLoaderService、AccountManagerService、ContentService、DropBoxManagerService、VibratorService、AlarmManagerService、Watchdog、 InputManagerService、WindowManagerService、IpConnectivityMetrics、NetworkWatchlistService、PinnerService等服务。

4cda35975dbcdfdbf81347f6904ba775.jpeg

SystemServer 的其他服务

2.startOtherServices 代码

  1. /**
  2. * Starts a miscellaneous grab bag of stuff that has yet to be refactored
  3. * and organized.
  4. */
  5. private void startOtherServices() {
  6. ... ...
  7. traceBeginAndSlog("StartKeyAttestationApplicationIdProviderService");
  8. ServiceManager.addService("sec_key_att_app_id_provider",
  9. new KeyAttestationApplicationIdProviderService(context));
  10. traceEnd();
  11. // 启动 KeyChainSystemService
  12. traceBeginAndSlog("StartKeyChainSystemService");
  13. mSystemServiceManager.startService(KeyChainSystemService.class);
  14. traceEnd();
  15. traceBeginAndSlog("StartSchedulingPolicyService");
  16. ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
  17. traceEnd();
  18. // 启动 TelecomLoaderService
  19. traceBeginAndSlog("StartTelecomLoaderService");
  20. mSystemServiceManager.startService(TelecomLoaderService.class);
  21. traceEnd();
  22. traceBeginAndSlog("StartTelephonyRegistry");
  23. telephonyRegistry = new TelephonyRegistry(context);
  24. ServiceManager.addService("telephony.registry", telephonyRegistry);
  25. traceEnd();
  26. traceBeginAndSlog("StartEntropyMixer");
  27. mEntropyMixer = new EntropyMixer(context);
  28. traceEnd();
  29. mContentResolver = context.getContentResolver();
  30. // 启动 用户管理服务 ,必现在StartContentService 之前
  31. traceBeginAndSlog("StartAccountManagerService");
  32. mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
  33. traceEnd();
  34. // 启动 ContentService
  35. traceBeginAndSlog("StartContentService");
  36. mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
  37. traceEnd();
  38. // 安装系统Provider 例如 SettingProvider CantacttProvider
  39. traceBeginAndSlog("InstallSystemProviders");
  40. mActivityManagerService.installSystemProviders();
  41. // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
  42. SQLiteCompatibilityWalFlags.reset();
  43. traceEnd();
  44. // 启动 DropBoxManagerService
  45. // 由于 依赖SettingsProvider,必须在InstallSystemProviders之后启动
  46. traceBeginAndSlog("StartDropBoxManager");
  47. mSystemServiceManager.startService(DropBoxManagerService.class);
  48. traceEnd();
  49. //启动 VibratorService 震动服务
  50. traceBeginAndSlog("StartVibratorService");
  51. vibrator = new VibratorService(context);
  52. ServiceManager.addService("vibrator", vibrator);
  53. traceEnd();
  54. if (!isWatch) {
  55. traceBeginAndSlog("StartConsumerIrService");
  56. consumerIr = new ConsumerIrService(context);
  57. ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
  58. traceEnd();
  59. }
  60. // 启动 AlarmManagerService
  61. traceBeginAndSlog("StartAlarmManagerService");
  62. if(!sMtkSystemServerIns.startMtkAlarmManagerService()){
  63. mSystemServiceManager.startService(AlarmManagerService.class);
  64. }
  65. traceEnd();
  66. // 初始化 看门狗
  67. traceBeginAndSlog("InitWatchdog");
  68. final Watchdog watchdog = Watchdog.getInstance();
  69. watchdog.init(context, mActivityManagerService);
  70. traceEnd();
  71. //启动 InputManagerService
  72. traceBeginAndSlog("StartInputManagerService");
  73. inputManager = new InputManagerService(context);
  74. traceEnd();
  75. //启动 WindowManagerService
  76. traceBeginAndSlog("StartWindowManagerService");
  77. // WMS needs sensor service ready
  78. ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
  79. mSensorServiceStart = null;
  80. wm = WindowManagerService.main(context, inputManager,
  81. mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
  82. !mFirstBoot, mOnlyCore, new PhoneWindowManager());
  83. ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
  84. DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
  85. ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
  86. /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
  87. traceEnd();
  88. traceBeginAndSlog("SetWindowManagerService");
  89. mActivityManagerService.setWindowManager(wm);
  90. traceEnd();
  91. traceBeginAndSlog("WindowManagerServiceOnInitReady");
  92. wm.onInitReady();
  93. traceEnd();
  94. // Start receiving calls from HIDL services. Start in in a separate thread
  95. // because it need to connect to SensorManager. This have to start
  96. // after START_SENSOR_SERVICE is done.
  97. SystemServerInitThreadPool.get().submit(() -> {
  98. TimingsTraceLog traceLog = new TimingsTraceLog(
  99. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  100. traceLog.traceBegin(START_HIDL_SERVICES);
  101. startHidlServices();
  102. traceLog.traceEnd();
  103. }, START_HIDL_SERVICES);
  104. if (!isWatch) {
  105. traceBeginAndSlog("StartVrManagerService");
  106. mSystemServiceManager.startService(VrManagerService.class);
  107. traceEnd();
  108. }
  109. traceBeginAndSlog("StartInputManager");
  110. inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
  111. inputManager.start();
  112. traceEnd();
  113. // TODO: Use service dependencies instead.
  114. traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady");
  115. mDisplayManagerService.windowManagerAndInputReady();
  116. traceEnd();
  117. // Skip Bluetooth if we have an emulator kernel
  118. // TODO: Use a more reliable check to see if this product should
  119. // support Bluetooth - see bug 988521
  120. if (isEmulator) {
  121. Slog.i(TAG, "No Bluetooth Service (emulator)");
  122. } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
  123. Slog.i(TAG, "No Bluetooth Service (factory test)");
  124. } else if (!context.getPackageManager().hasSystemFeature
  125. (PackageManager.FEATURE_BLUETOOTH)) {
  126. Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
  127. } else {
  128. traceBeginAndSlog("StartBluetoothService");
  129. mSystemServiceManager.startService(BluetoothService.class);
  130. traceEnd();
  131. }
  132. // 启动 IpConnectivityMetrics
  133. traceBeginAndSlog("IpConnectivityMetrics");
  134. mSystemServiceManager.startService(IpConnectivityMetrics.class);
  135. traceEnd();
  136. // 启动 NetworkWatchlistService
  137. traceBeginAndSlog("NetworkWatchlistService");
  138. mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
  139. traceEnd();
  140. // 启动 PinnerService
  141. traceBeginAndSlog("PinnerService");
  142. mSystemServiceManager.startService(PinnerService.class);
  143. traceEnd();
  144. } catch (RuntimeException e) {

参考文献:

【腾讯文档】Android Framework 知识库
https://docs.qq.com/doc/DSXBmSG9VbEROUXF5

友情推荐:

Android 开发干货集锦

至此,本篇已结束。转载网络的文章,小编觉得很优秀,欢迎点击阅读原文,支持原创作者,如有侵权,恳请联系小编删除,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!

5543571b9006a08effc8777e257dd682.jpeg

点击阅读原文,为大佬点赞!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/227818
推荐阅读
相关标签
  

闽ICP备14008679号