经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Zygote家的大儿子 —— SystemServer
来源:cnblogs  作者:秉心说  时间:2019/10/14 9:40:25  对本文有异议

本文基于 Android 9.0 , 代码仓库地址 : android_9.0.0_r45

文中源码链接:

SystemServer.java

SystemServiceManager.java

SystemService.java

首先来回顾一下上篇文章 Java 世界的盘古和女娲 —— Zygote ,主要介绍了 Android 世界中的第一个 Java 进程 Zygote,它的主要工作流程如下:

  1. registerServerSocketFromEnv(), 注册服务端 socket,用于和客户端进程通信
  2. preload(),预加载一系列资源,提高应用启动速度
  3. forkSystemServer(),创建 system_server 进程
  4. 功成身退,调用 runSelectLoop() 等待响应客户端请求,创建应用进程

本篇文章的主角 system_server 进程是 Zygote 进程 fork 出的第一个进程,它负责管理和启动整个 Framework 层。

再来看看 Gityuan 的这张图片,找一下 System Server 的位置,它承载了各类系统服务的创建和启动。关于 system_server 进程的创建流程,上篇文章中已经做了详细介绍,这里再简单看一下流程图:

最终会调用到 SystemServer.main() 方法。下面就以此为起点,来具体分析 SystemServer 都做了些什么。

SystemServer 启动流程

  1. public static void main(String[] args) {
  2. new SystemServer().run();
  3. }

接着看 run() 方法。

  1. private void run() {
  2. try {
  3. ......
  4. // 如果设备时间早于 1970 年,很多 API 处理负数时会 crash。所以直接设置为 1970 年 1 月 1 日
  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. // 未设置时区的话默认设为 GMT
  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. if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  17. final String languageTag = Locale.getDefault().toLanguageTag();
  18. SystemProperties.set("persist.sys.locale", languageTag);
  19. SystemProperties.set("persist.sys.language", "");
  20. SystemProperties.set("persist.sys.country", "");
  21. SystemProperties.set("persist.sys.localevar", "");
  22. }
  23. // The system server should never make non-oneway calls
  24. Binder.setWarnOnBlocking(true);
  25. // The system server should always load safe labels
  26. PackageItemInfo.setForceSafeLabels(true);
  27. // Default to FULL within the system server.
  28. SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
  29. // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
  30. SQLiteCompatibilityWalFlags.init(null);
  31. // Here we go!
  32. Slog.i(TAG, "Entered the Android system server!");
  33. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  34. EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
  35. if (!mRuntimeRestart) {
  36. MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
  37. }
  38. // 设置虚拟机运行库路径
  39. SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
  40. // Mmmmmm... more memory!
  41. // 清除虚拟机内存增长限制,允许应用申请更多内存
  42. VMRuntime.getRuntime().clearGrowthLimit();
  43. // 设置堆内存的有效利用率为 0.8,(可能被忽略)
  44. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  45. // 确保指纹信息已经定义
  46. Build.ensureFingerprintProperty();
  47. // Within the system server, it is an error to access Environment paths without
  48. // explicitly specifying a user.
  49. Environment.setUserRequired(true);
  50. // Within the system server, any incoming Bundles should be defused
  51. // to avoid throwing BadParcelableException.
  52. BaseBundle.setShouldDefuse(true);
  53. // Within the system server, when parceling exceptions, include the stack trace
  54. Parcel.setStackTraceParceling(true);
  55. // 确保系统的 Binder 调用总是运行在前台优先级
  56. BinderInternal.disableBackgroundScheduling(true);
  57. // Increase the number of binder threads in system_server
  58. BinderInternal.setMaxThreads(sMaxBinderThreads);
  59. // Prepare the main looper thread (this thread).
  60. android.os.Process.setThreadPriority(
  61. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  62. android.os.Process.setCanSelfBackground(false);
  63. // 1. 创建主线程 Looper
  64. Looper.prepareMainLooper();
  65. Looper.getMainLooper().setSlowLogThresholdMs(
  66. SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
  67. // 初始化 native 服务,加载 libandroid_servers.so
  68. System.loadLibrary("android_servers");
  69. // 检查上次关机是否失败,可能不会有返回值
  70. performPendingShutdown();
  71. // 2. 初始化系统上下文
  72. createSystemContext();
  73. // 3. 创建系统服务管理 SystemServiceManager
  74. // 并将 mSystemServiceManager 注册到 sLocalServiceObjects 中
  75. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  76. mSystemServiceManager.setStartInfo(mRuntimeRestart,
  77. mRuntimeStartElapsedTime, mRuntimeStartUptime);
  78. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  79. // Prepare the thread pool for init tasks that can be parallelized
  80. SystemServerInitThreadPool.get();
  81. } finally {
  82. traceEnd(); // InitBeforeStartServices
  83. }
  84. // Start services.
  85. try {
  86. traceBeginAndSlog("StartServices");
  87. startBootstrapServices(); // 4. 启动系统引导服务
  88. startCoreServices(); // 5. 启动系统核心服务
  89. startOtherServices(); // 6. 启动其他服务
  90. SystemServerInitThreadPool.shutdown();
  91. } catch (Throwable ex) {
  92. Slog.e("System", "******************************************");
  93. Slog.e("System", "************ Failure starting system services", ex);
  94. throw ex;
  95. } finally {
  96. traceEnd();
  97. }
  98. StrictMode.initVmDefaults(null);
  99. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  100. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  101. MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
  102. final int MAX_UPTIME_MILLIS = 60 * 1000;
  103. if (uptimeMillis > MAX_UPTIME_MILLIS) {
  104. Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
  105. "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
  106. }
  107. }
  108. // 7. Loop forever.
  109. Looper.loop();
  110. throw new RuntimeException("Main thread loop unexpectedly exited");
  111. }

代码虽然比较长,但是逻辑很清晰。我在注释里标记了比较重要的 7 个步骤,逐一分析。

Looper.prepareMainLooper()

初始化 Looper。关于 Handler 消息机制,可以阅读我的另一篇文章 深入理解 Handler 消息机制 。最后会调用 Looper.loop() 开启消息循环,开始处理消息。

createSystemContext()

  1. private void createSystemContext() {
  2. // 创建 system_server 上下文信息
  3. ActivityThread activityThread = ActivityThread.systemMain();
  4. mSystemContext = activityThread.getSystemContext();
  5. mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
  6. final Context systemUiContext = activityThread.getSystemUiContext();
  7. // 设置主题,用于系统 dialog 等
  8. systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
  9. }

创建系统上下文。首先调用 ActivityThread.systemMain() 方法获取 ActivityThread 对象,然后再获取上下文。

  1. public static ActivityThread systemMain() {
  2. // 判断是否是大内存设备,在低内存设备上不启用硬件加速
  3. if (!ActivityManager.isHighEndGfx()) {
  4. ThreadedRenderer.disable(true);
  5. } else {
  6. ThreadedRenderer.enableForegroundTrimming();
  7. }
  8. ActivityThread thread = new ActivityThread();
  9. thread.attach(true, 0);
  10. return thread;
  11. }

关于 ActivityThread.attach() 方法这里不做具体分析了,后面文章说到应用启动时再来详细解析。

创建完系统上下文,接下来就是启动各种系统服务了。源码中把服务大致分为了三类,再来回顾一下:

  1. startBootstrapServices(); // 4. 启动系统引导服务
  2. startCoreServices(); // 5. 启动系统核心服务
  3. startOtherServices(); // 6. 启动其他服务

逐一进行分析。

startBootstrapServices()

  1. private void startBootstrapServices() {
  2. final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
  3. SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
  4. // 阻塞等待与 installd 建立 socket 通道
  5. Installer installer = mSystemServiceManager.startService(Installer.class);
  6. // 启动 DeviceIdentifiersPolicyService,在 ActivityManagerService 之前
  7. mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
  8. // 启动服务 ActivityManagerService
  9. mActivityManagerService = mSystemServiceManager.startService(
  10. ActivityManagerService.Lifecycle.class).getService();
  11. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  12. mActivityManagerService.setInstaller(installer);
  13. // 启动服务 PowerManagerService
  14. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
  15. // Now that the power manager has been started, let the activity manager
  16. // initialize power management features.
  17. mActivityManagerService.initPowerManagement();
  18. // 启动服务 RecoverySystemService
  19. mSystemServiceManager.startService(RecoverySystemService.class);
  20. // Now that we have the bare essentials of the OS up and running, take
  21. // note that we just booted, which might send out a rescue party if
  22. // we're stuck in a runtime restart loop.
  23. RescueParty.noteBoot(mSystemContext);
  24. // 启动服务 LightsService
  25. mSystemServiceManager.startService(LightsService.class);
  26. // Package manager isn't started yet; need to use SysProp not hardware feature
  27. if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
  28. mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
  29. }
  30. // 启动 DisplayManagerService,在 PackageManagerService 之前
  31. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
  32. // We need the default display before we can initialize the package manager.
  33. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  34. // 正在加密设备时只运行核心 app
  35. String cryptState = SystemProperties.get("vold.decrypt");
  36. if (ENCRYPTING_STATE.equals(cryptState)) {
  37. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  38. mOnlyCore = true;
  39. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  40. Slog.w(TAG, "Device encrypted - only parsing core apps");
  41. mOnlyCore = true;
  42. }
  43. // 启动服务 PackageManagerService
  44. if (!mRuntimeRestart) {
  45. MetricsLogger.histogram(null, "boot_package_manager_init_start",
  46. (int) SystemClock.elapsedRealtime());
  47. }
  48. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  49. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  50. mFirstBoot = mPackageManagerService.isFirstBoot();
  51. mPackageManager = mSystemContext.getPackageManager();
  52. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  53. MetricsLogger.histogram(null, "boot_package_manager_init_ready",
  54. (int) SystemClock.elapsedRealtime());
  55. }
  56. if (!mOnlyCore) {
  57. boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
  58. false);
  59. if (!disableOtaDexopt) {
  60. traceBeginAndSlog("StartOtaDexOptService");
  61. try {
  62. OtaDexoptService.main(mSystemContext, mPackageManagerService);
  63. } catch (Throwable e) {
  64. reportWtf("starting OtaDexOptService", e);
  65. } finally {
  66. traceEnd();
  67. }
  68. }
  69. }
  70. // 启动服务 UserManagerService
  71. mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
  72. // 初始化属性 cache 以缓存包资源
  73. AttributeCache.init(mSystemContext);
  74. // 设置 AMS
  75. mActivityManagerService.setSystemProcess();
  76. // DisplayManagerService needs to setup android.display scheduling related policies
  77. // since setSystemProcess() would have overridden policies due to setProcessGroup
  78. mDisplayManagerService.setupSchedulerPolicies();
  79. // 启动服务 OverlayManagerService
  80. OverlayManagerService overlayManagerService = new OverlayManagerService(
  81. mSystemContext, installer);
  82. mSystemServiceManager.startService(overlayManagerService);
  83. if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
  84. // DisplayManager needs the overlay immediately.
  85. overlayManagerService.updateSystemUiContext();
  86. LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
  87. }
  88. // 在单独的线程中启动 SensorService
  89. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
  90. TimingsTraceLog traceLog = new TimingsTraceLog(
  91. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  92. startSensorService();
  93. }, START_SENSOR_SERVICE);
  94. }

startBootstrapServices() 方法中的都是系统启动过程中的关键服务,且相互依赖,主要下列服务 :

Installer DeviceIdentifiersPolicyService ActivityManagerService PowerManagerService RecoverySystemService LightsService StartSidekickService DisplayManagerService

SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY (100)

PackageManagerService UserManagerService OverlayManagerService SensorService

一共启动了十二个核心服务。注意中间的 SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY,它并不是代表什么系统服务,而是一个 int 值 100,类似的 int 值还有一些,定义在 SystemService 类中,它的作用是给服务启动过程划分阶段,每个阶段都有特定的含义,可以做不同的事情。这里先混个脸熟,等介绍完所有的服务,再回过头来总结一下有哪些阶段。

startCoreServices()

  1. private void startCoreServices() {
  2. // 启动服务 BatteryService,需要 LightService
  3. mSystemServiceManager.startService(BatteryService.class);
  4. // 启动服务 UsageStatsService,统计应用使用情况
  5. mSystemServiceManager.startService(UsageStatsService.class);
  6. mActivityManagerService.setUsageStatsManager(
  7. LocalServices.getService(UsageStatsManagerInternal.class));
  8. // 检查是否存在可更新的 WebView。存在就启动服务 WebViewUpdateService
  9. if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
  10. mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
  11. }
  12. // 启动服务 BinderCallsStatsService,跟踪 Binder 调用的 cpu 时间消耗
  13. BinderCallsStatsService.start();
  14. }

启动了四个服务,BatteryService UsageStatsService WebViewUpdateServiceBinderCallsStatsService

startOtherServices()

startOtherServices() 源码有一千多行,就像一个杂货铺,启动了一系列的服务。下面尽量精简一下代码:

  1. KeyAttestationApplicationIdProviderService/KeyChainSystemService
  2. SchedulingPolicyService/TelecomLoaderService/TelephonyRegistry
  3. mContentResolver = context.getContentResolver();
  4. AccountManagerService/ContentService
  5. mActivityManagerService.installSystemProviders();
  6. DropBoxManagerService/VibratorService/ConsumerIrService/AlarmManagerService
  7. final Watchdog watchdog = Watchdog.getInstance();
  8. watchdog.init(context, mActivityManagerService);
  9. InputManagerService/WindowManagerService/VrManagerService/BluetoothService
  10. IpConnectivityMetrics/NetworkWatchlistService/PinnerService
  11. InputMethodManagerService/AccessibilityManagerService/StorageManagerService
  12. StorageStatsService/UiModeManagerService/LockSettingsService
  13. PersistentDataBlockService/OemLockService/DeviceIdleController
  14. DevicePolicyManagerService/StatusBarManagerService/ClipboardService
  15. NetworkManagementService/IpSecService/TextServicesManagerService
  16. TextClassificationManagerService/NetworkScoreService/NetworkStatsService
  17. NetworkPolicyManagerService/WifiScanningService/RttService
  18. WifiAware/WifiP2P/Lowpan/Ethernet/ConnectivityService/NsdService
  19. SystemUpdateManagerService/UpdateLockService/NotificationManagerService
  20. DeviceStorageMonitorService/LocationManagerService/CountryDetectorService
  21. SearchManagerService/WallpaperManagerService/AudioService/BroadcastRadioService
  22. DockObserver/ThermalObserver/WiredAccessoryManager/MidiManager/UsbService
  23. SerialService/HardwarePropertiesManagerService/TwilightService
  24. ColorDisplayService/JobSchedulerService/SoundTriggerService/TrustManagerService
  25. BackupManager/AppWidgerService/VoiceRecognitionManager/GestureLauncherService
  26. SensorNotificationService/ContextHubSystemService/DiskStatsService
  27. TimeZoneRulesManagerService/NetworkTimeUpdateService/CommonTimeManagementService
  28. CertBlacklister/EmergencyAffordanceService/DreamManagerService/GraphicsStatsService
  29. CoverageService/PrintManager/CompanionDeviceManager/RestrictionsManagerService
  30. MediaSessionService/MediaUpdateService/HdmiControlService/TvInputManagerService
  31. MediaResourceMonitorService/TvRemoteService/MediaRouterService/FingerprintService
  32. BackgroundDexOptService/PruneInstantAppsJobService/ShortcutService
  33. LauncherAppsService/CrossProfileAppsService/MediaProjectionManagerService
  34. WearConfigService/WearConnectivityService/WearTimeService/WearLeftyService
  35. WearGlobalActionsService/SliceManagerService/CameraServiceProxy/IoTSystemService
  36. MmsServiceBroker/AutoFillService
  37. // It is now time to start up the app processes...
  38. vibrator.systemReady();
  39. lockSettings.systemReady();
  40. // 480
  41. mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
  42. // 500
  43. mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
  44. wm.systemReady();
  45. mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
  46. mPackageManagerService.systemReady();
  47. mDisplayManagerService.systemReady(safeMode, mOnlyCore);
  48. // Start device specific services
  49. final String[] classes = mSystemContext.getResources().getStringArray(
  50. R.array.config_deviceSpecificSystemServices);
  51. for (final String className : classes) {
  52. try {
  53. mSystemServiceManager.startService(className);
  54. } catch (Throwable e) {
  55. reportWtf("starting " + className, e);
  56. }
  57. }
  58. // 520
  59. mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
  60. mActivityManagerService.systemReady(() -> {
  61. // 550
  62. mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
  63. startSystemUi(context, windowManagerF);
  64. networkManagementF.systemReady();
  65. ipSecServiceF.systemReady();
  66. networkStatsF.systemReady();
  67. connectivityF.systemReady();
  68. Watchdog.getInstance().start
  69. mPackageManagerService.waitForAppDataPrepared();
  70. // 600
  71. mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
  72. locationF.systemRunning();
  73. countryDetectorF.systemRunning();
  74. networkTimeUpdaterF.systemRunning();
  75. commonTimeMgmtServiceF.systemRunning();
  76. inputManagerF.systemRunning();
  77. telephonyRegistryF.systemRunning();
  78. mediaRouterF.systemRunning();
  79. mmsServiceF.systemRunning();
  80. incident.systemRunning();
  81. }

通过上面的代码可以看到启动了相当多的系统服务。startOtherServices() 方法共经历了五个启动阶段,如下所示:

  1. SystemService.PHASE_LOCK_SETTINGS_READY // 480
  2. SystemService.PHASE_SYSTEM_SERVICES_READY // 500
  3. SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY // 520
  4. SystemService.PHASE_ACTIVITY_MANAGER_READY // 550
  5. SystemService.PHASE_THIRD_PARTY_APPS_CAN_START // 600

最后调用的 mActivityManagerService.systemReady() 方法。该方法中会调用 startHomeActivityLocked 来启动桌面 Activity,这样桌面应用就启动了。

Looper.loop()

至此,system_server 进程的主要工作就算完成了,进入 Looper.loop() 状态,等待其他线程通过 Handler 发送消息到主线程并处理。

SystemServer 启动阶段分类

回过头再来看看前面提到的启动阶段分类,定义在 com.android.server.SystemService 类中:

  1. /*
  2. * Boot Phases
  3. *
  4. * 启动阶段
  5. */
  6. public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?
  7. /**
  8. * After receiving this boot phase, services can obtain lock settings data.
  9. */
  10. public static final int PHASE_LOCK_SETTINGS_READY = 480;
  11. /**
  12. * After receiving this boot phase, services can safely call into core system services
  13. * such as the PowerManager or PackageManager.
  14. *
  15. * 在这个阶段之后,可以安全的调用系统核心服务,如 PowerManager 和 PackageManager
  16. */
  17. public static final int PHASE_SYSTEM_SERVICES_READY = 500;
  18. /**
  19. * After receiving this boot phase, services can safely call into device specific services.
  20. *
  21. * 在这个阶段之后,可以安全调用设备特定的服务
  22. */
  23. public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;
  24. /**
  25. * After receiving this boot phase, services can broadcast Intents.
  26. *
  27. * 在这个阶段之后,服务可以广播
  28. */
  29. public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
  30. /**
  31. * After receiving this boot phase, services can start/bind to third party apps.
  32. * Apps will be able to make Binder calls into services at this point.
  33. *
  34. * 在这个阶段之后,服务可以启动/绑定第三方应用
  35. * 应用此时可以进行 Binder 调用
  36. */
  37. public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
  38. /**
  39. * After receiving this boot phase, services can allow user interaction with the device.
  40. * This phase occurs when boot has completed and the home application has started.
  41. * System services may prefer to listen to this phase rather than registering a
  42. * broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
  43. *
  44. * 在这个阶段之后,允许用户和设备交互。
  45. * 这个阶段发生在启动完成,home 应用已经开始。
  46. * 系统服务更倾向于监听这个阶段,而不是监听启动广播 ACTION_BOOT_COMPLETED,以降低延迟
  47. */
  48. public static final int PHASE_BOOT_COMPLETED = 1000;

system_server 启动过程中各个阶段的位置大致如下:

  1. private void startBootstrapServices() {
  2. ...
  3. // 100
  4. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  5. ...
  6. }
  7. private void startOtherServices() {
  8. ...
  9. // 480
  10. mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
  11. // 500
  12. mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
  13. ...
  14. // 520
  15. mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
  16. mActivityManagerService.systemReady(() -> {
  17. mSystemServiceManager.startBootPhase(
  18. SystemService.PHASE_ACTIVITY_MANAGER_READY); // 550
  19. ...
  20. mSystemServiceManager.startBootPhase(
  21. SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); // 600
  22. }
  23. }

最后的 SystemService.PHASE_BOOT_COMPLETED(1000) 在 AMS 的 finishBooting() 方法中调用。另外注意 480500 两个阶段是连在一起的,中间没有发生任何事情。

那么,划分阶段的具体作用是什么呢?答案就在 startBootPhase() 方法中:

  1. public void startBootPhase(final int phase) {
  2. if (phase <= mCurrentPhase) {
  3. throw new IllegalArgumentException("Next phase must be larger than previous");
  4. }
  5. mCurrentPhase = phase;
  6. try {
  7. final int serviceLen = mServices.size();
  8. for (int i = 0; i < serviceLen; i++) {
  9. final SystemService service = mServices.get(i);
  10. long time = SystemClock.elapsedRealtime();
  11. try {
  12. // 回调系统服务的 onBootPhase() 方法
  13. service.onBootPhase(mCurrentPhase);
  14. } catch (Exception ex) {
  15. throw new RuntimeException("Failed to boot service "
  16. + service.getClass().getName()
  17. + ": onBootPhase threw an exception during phase "
  18. + mCurrentPhase, ex);
  19. }
  20. warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
  21. }
  22. } finally {
  23. Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
  24. }
  25. }

核心就在于 service.onBootPhase(mCurrentPhase);。所有系统服务都是继承于 SystemService 的,startBootPhase() 方法会回调当前阶段已经加入 mServices 的所有系统服务的 onBootPhase() 方法,在合适的阶段做一些合适的事情。以 AMS 为例:

  1. @Override
  2. public void onBootPhase(int phase) {
  3. mService.mBootPhase = phase;
  4. if (phase == PHASE_SYSTEM_SERVICES_READY) {
  5. mService.mBatteryStatsService.systemServicesReady();
  6. mService.mServices.systemServicesReady();
  7. }
  8. }

SystemServer 是如何启动服务的 ?

看完 SystemServer 的源码,它最重要的工作就是创建和启动各种系统服务。那么服务一般是如何创建的呢?下面以 startBootstrapServices() 中创建的第一个服务 Installer 为例来看一下:

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

进入 SystemServiceManagerstartService() 方法:

  1. public <T extends SystemService> T startService(Class<T> serviceClass) {
  2. try {
  3. // 获取服务名称
  4. final String name = serviceClass.getName();
  5. // Create the service.
  6. if (!SystemService.class.isAssignableFrom(serviceClass)) {
  7. throw new RuntimeException("Failed to create " + name
  8. + ": service must extend " + SystemService.class.getName());
  9. }
  10. final T service;
  11. try {
  12. // 获取服务类的构造器
  13. Constructor<T> constructor = serviceClass.getConstructor(Context.class);
  14. // 反射创建 service
  15. service = constructor.newInstance(mContext);
  16. } catch (InstantiationException ex) {
  17. throw new RuntimeException("Failed to create service " + name
  18. + ": service could not be instantiated", ex);
  19. } catch (IllegalAccessException ex) {
  20. throw new RuntimeException("Failed to create service " + name
  21. + ": service must have a public constructor with a Context argument", ex);
  22. } catch (NoSuchMethodException ex) {
  23. throw new RuntimeException("Failed to create service " + name
  24. + ": service must have a public constructor with a Context argument", ex);
  25. } catch (InvocationTargetException ex) {
  26. throw new RuntimeException("Failed to create service " + name
  27. + ": service constructor threw an exception", ex);
  28. }
  29. startService(service);
  30. return service;
  31. } finally {
  32. Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
  33. }
  34. }

创建并启动一个系统服务。这个系统服务必须是 com.android.server.SystemService 的子类。根据参数传入的 Class 对象反射创建其实例,再调用重载方法 startService()

  1. public void startService(@NonNull final SystemService service) {
  2. // Register it.
  3. mServices.add(service);
  4. // Start it.
  5. long time = SystemClock.elapsedRealtime();
  6. try {
  7. // 回调系统服务的 onStart() 方法
  8. service.onStart();
  9. } catch (RuntimeException ex) {
  10. throw new RuntimeException("Failed to start service " + service.getClass().getName()
  11. + ": onStart threw an exception", ex);
  12. }
  13. warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
  14. }

就两步。第一步,注册服务,mServices 是一个 ArrayList<SystemService> 对象,用来保存已经创建的系统服务。第二步,回调服务的 onStart() 方法,还是以 Installer 为例:

  1. @Override
  2. public void onStart() {
  3. if (mIsolated) {
  4. mInstalld = null;
  5. } else {
  6. connect();
  7. }
  8. }

这样一个服务就启动完成了。这是一种比较普遍的启动方式,当然还有一些系统服务具有不一样的启动方式,这里就不一一分析了,后面有机会解析具体服务的时候再来分析。

总结

SystemServer 的启动流程比较耿直,没有那么多弯弯绕,下面简单总结一下:

  1. 语言、时区、地区等设置
  2. 虚拟机内存设置
  3. 指纹信息,Binder 调用设置
  4. Looper.prepareMainLooper() ,创建主线程 Looper
  5. 初始化 native 服务,加载 libandroid_servers.so
  6. createSystemContext(),初始化系统上下文
  7. 创建系统服务管理 SystemServiceManager
  8. startBootstrapServices,启动系统引导服务
  9. startCoreServices,启动系统核心服务
  10. startOtherServices,启动其他服务
  11. Looper.loop(),开启消息循环

另外,在 startOtherServices 的最后会调用 AMS 的 onSystemReady() 方法启动桌面 Activity。

预告

还记得 Zygote 进程的 runSelectLoop() 方法吗?Zygote 在创建完 system_server 进程之后,就开始默默的等待客户端请求创建应用进程。下一篇,我们将从源码角度来捋一遍客户端是如何发送请求,Zygote 是如何处理请求,应用进程是如何创建的,敬请期待!

文章首发微信公众号: 秉心说 , 专注 Java 、 Android 原创知识分享,LeetCode 题解。

更多最新原创文章,扫码关注我吧!

原文链接:http://www.cnblogs.com/bingxinshuo/p/11669031.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号