Android SystemServer学习笔记

版本:Android O

SystemServer和Zygote是Android java世界的两大支柱,SystemServer是Zygote孵化出来的进程,进程名为system_server,几乎所有的系统服务都在该进程中,eg:AMS,PMS,WMS .etc

1 分析SystemServer代码

1.1 从SystemServer.java分析

源码位置:frameworks\base\services\java\com\android\server\SystemServer.java,从main()函数开始分析:

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

new出一个SystemServer类,执行其run()方法.

  1. public SystemServer() {
  2. // Check for factory test mode.
  3. mFactoryTestMode = FactoryTest.getMode();
  4. // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
  5. mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
  6. }

这是SystemServer的构造方法,具体没有研究,有blog说SystemServer.java是final的,不能被继承,但是在O中不是(也没有具体研究,研究了再补充).接下来看run()方法:

  1. private void run() {
  2. try {
  3. traceBeginAndSlog("InitBeforeStartServices");
  4. // If a device's clock is before 1970 (before 0), a lot of
  5. // APIs crash dealing with negative numbers, notably
  6. // java.io.File#setLastModified, so instead we fake it and
  7. // hope that time from cell towers or NTP fixes it shortly.
  8. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  9. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  10. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  11. }
  12. //
  13. // Default the timezone property to GMT if not set.
  14. //
  15. String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  16. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  17. Slog.w(TAG, "Timezone not set; setting to GMT.");
  18. SystemProperties.set("persist.sys.timezone", "GMT");
  19. }
  20. // If the system has "persist.sys.language" and friends set, replace them with
  21. // "persist.sys.locale". Note that the default locale at this point is calculated
  22. // using the "-Duser.locale" command line flag. That flag is usually populated by
  23. // AndroidRuntime using the same set of system properties, but only the system_server
  24. // and system apps are allowed to set them.
  25. //
  26. // NOTE: Most changes made here will need an equivalent change to
  27. // core/jni/AndroidRuntime.cpp
  28. if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  29. final String languageTag = Locale.getDefault().toLanguageTag();
  30. SystemProperties.set("persist.sys.locale", languageTag);
  31. SystemProperties.set("persist.sys.language", "");
  32. SystemProperties.set("persist.sys.country", "");
  33. SystemProperties.set("persist.sys.localevar", "");
  34. }
  35. // The system server should never make non-oneway calls
  36. Binder.setWarnOnBlocking(true);
  37. // Here we go!
  38. Slog.i(TAG, "Entered the Android system server!");
  39. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  40. EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
  41. if (!mRuntimeRestart) {
  42. MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
  43. }
  44. /// M: BOOTPROF
  45. addBootEvent("Android:SysServerInit_START");
  46. // In case the runtime switched since last boot (such as when
  47. // the old runtime was removed in an OTA), set the system
  48. // property so that it is in sync. We can | xq oqi't do this in
  49. // libnativehelper's JniInvocation::Init code where we already
  50. // had to fallback to a different runtime because it is
  51. // running as root and we need to be the system user to set
  52. // the property. http://b/11463182
  53. SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
  54. // Enable the sampling profiler.
  55. if (SamplingProfilerIntegration.isEnabled()) {
  56. SamplingProfilerIntegration.start();
  57. mProfilerSnapshotTimer = new Timer();
  58. mProfilerSnapshotTimer.schedule(new TimerTask() {
  59. @Override
  60. public void run() {
  61. SamplingProfilerIntegration.writeSnapshot("system_server", null);
  62. }
  63. }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
  64. }
  65. // Mmmmmm... more memory!
  66. VMRuntime.getRuntime().clearGrowthLimit();
  67. // The system server has to run all of the time, so it needs to be
  68. // as efficient as possible with its memory usage.
  69. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  70. // Some devices rely on runtime fingerprint generation, so make sure
  71. // we've defined it before booting further.
  72. Build.ensureFingerprintProperty();
  73. // Within the system server, it is an error to access Environment paths without
  74. // explicitly specifying a user.
  75. Environment.setUserRequired(true);
  76. // Within the system server, any incoming Bundles should be defused
  77. // to avoid throwing BadParcelableException.
  78. BaseBundle.setShouldDefuse(true);
  79. // Ensure binder calls into the system always run at foreground priority.
  80. BinderInternal.disableBackgroundScheduling(true);
  81. // Increase the number of binder threads in system_server
  82. BinderInternal.setMaxThreads(sMaxBinderThreads);
  83. // Prepare the main looper thread (this thread).
  84. android.os.Process.setThreadPriority(
  85. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  86. android.os.Process.setCanSelfBackground(false);
  87. //开启消息循环
  88. Looper.prepareMainLooper();
  89. // Initialize native services.
  90. System.loadLibrary("android_servers");
  91. // Check whether we failed to shut down last time we tried.
  92. // This call may not return.
  93. performPendingShutdown();
  94. // Initialize the system context.
  95. createSystemContext();
  96. // Create the system service manager.
  97. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  98. mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
  99. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  100. // Prepare the thread pool for init tasks that can be parallelized
  101. SystemServerInitThreadPool.get();
  102. } finally {
  103. traceEnd(); // InitBeforeStartServices
  104. }
  105. //创建服务
  106. // Start services.
  107. try {
  108. traceBeginAndSlog("StartServices");
  109. startBootstrapServices();
  110. startCoreServices();
  111. startOtherServices();
  112. SystemServerInitThreadPool.shutdown();
  113. } catch (Throwable ex) {
  114. Slog.e("System", "******************************************");
  115. Slog.e("System", "************ Failure starting system services", ex);
  116. throw ex;
  117. } finally {
  118. traceEnd();
  119. }
  120. // For debug builds, log event loop stalls to dropbox for analysis.
  121. if (StrictMode.conditionallyEnableDebugLogging()) {
  122. Slog.i(TAG, "Enabled StrictMode for system server main thread.");
  123. }
  124. /// M: open wtf when load is user or userdebug.
  125. if (!"eng".equals(Build.TYPE) && !mRuntimeRestart && !isFirstBootOrUpgrade()) {
  126. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  127. MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
  128. final int MAX_UPTIME_MILLIS = 60 * 1000;
  129. if (uptimeMillis > MAX_UPTIME_MILLIS) {
  130. Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
  131. "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
  132. }
  133. }
  134. /// M: BOOTPROF
  135. addBootEvent("Android:SysServerInit_END");
  136. // Loop forever.
  137. Looper.loop();
  138. throw new RuntimeException("Main thread loop unexpectedly exited");
  139. }

最终的实现实在run方法里面,接下来分块分析run方法:

  1. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  2. Slog.w(TAG, "System clock is before 1970; setting to 1970.");
  3. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  4. }

为了判断系统时钟是否早于1970/01/01/00:00,如果早于这个时间,系统后面的处理可能会出问题,所以如果早于该时间,统一设置为1970/01/01/00:00

  1. String timezoneProperty = SystemProperties.get("persist.sys.timezone");
  2. if (timezoneProperty == null || timezoneProperty.isEmpty()) {
  3. Slog.w(TAG, "Timezone not set; setting to GMT.");
  4. SystemProperties.set("persist.sys.timezone", "GMT");
  5. }

如果没有设置时区,统一设置为GMT

  1. if (!SystemProperties.get("persist.sys.language").isEmpty()) {
  2. final String languageTag = Locale.getDefault().toLanguageTag();
  3. SystemProperties.set("persist.sys.locale", languageTag);
  4. SystemProperties.set("persist.sys.language", "");
  5. SystemProperties.set("persist.sys.country", "");
  6. SystemProperties.set("persist.sys.localevar", "");
  7. }

设置系统语言环境;

  1. // Here we go!
  2. Slog.i(TAG, "Entered the Android system server!");
  3. int uptimeMillis = (int) SystemClock.elapsedRealtime();
  4. EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
  5. if (!mRuntimeRestart) {
  6. MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
  7. }
  8. /// M: BOOTPROF
  9. addBootEvent("Android:SysServerInit_START");
  10. // In case the runtime switched since last boot (such as when
  11. // the old runtime was removed in an OTA), set the system
  12. // property so that it is in sync. We can | xq oqi't do this in
  13. // libnativehelper's JniInvocation::Init code where we already
  14. // had to fallback to a different runtime because it is
  15. // running as root and we need to be the system user to set
  16. // the property. http://b/11463182
  17. SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
  18. // Enable the sampling profiler.
  19. if (SamplingProfilerIntegration.isEnabled()) {
  20. SamplingProfilerIntegration.start();
  21. mProfilerSnapshotTimer = new Timer();
  22. mProfilerSnapshotTimer.schedule(new TimerTask() {
  23. @Override
  24. public void run() {
  25. SamplingProfilerIntegration.writeSnapshot("system_server", null);
  26. }
  27. }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
  28. }
  29. // Mmmmmm... more memory!
  30. VMRuntime.getRuntime().clearGrowthLimit();
  31. // The system server has to run all of the time, so it needs to be
  32. // as efficient as possible with its memory usage.
  33. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
  34. // Some devices rely on runtime fingerprint generation, so make sure
  35. // we've defined it before booting further.
  36. Build.ensureFingerprintProperty();
  37. // Within the system server, it is an error to access Environment paths without
  38. // explicitly specifying a user.
  39. Environment.setUserRequired(true);
  40. // Within the system server, any incoming Bundles should be defused
  41. // to avoid throwing BadParcelableException.
  42. BaseBundle.setShouldDefuse(true);
  43. // Ensure binder calls into the system always run at foreground priority.
  44. BinderInternal.disableBackgroundScheduling(true);
  45. // Increase the number of binder threads in system_server
  46. BinderInternal.setMaxThreads(sMaxBinderThreads);

这段代码的主要作用是设置虚拟机(VMRuntime)运行内存,相关的操作,(没有细致的研究过).

  1. // Prepare the main looper thread (this thread).
  2. android.os.Process.setThreadPriority(
  3. android.os.Process.THREAD_PRIORITY_FOREGROUND);
  4. android.os.Process.setCanSelfBackground(false);
  5. Looper.prepareMainLooper();

创建消息循环,和ActivityThread.java里的main()函数里建立异步消息循环一样.

  1. // Initialize native services.
  2. System.loadLibrary("android_servers");

加载了libandroid_servers.so文件

  1. // Check whether we failed to shut down last time we tried.
  2. // This call may not return.
  3. performPendingShutdown();

performPendingShutdown()函数代码如下:

  1. private void performPendingShutdown() {
  2. final String shutdownAction = SystemProperties.get(
  3. ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
  4. if (shutdownAction != null && shutdownAction.length() > 0) {
  5. boolean reboot = (shutdownAction.charAt(0) == '1');
  6. final String reason;
  7. if (shutdownAction.length() > 1) {
  8. reason = shutdownAction.substring(1, shutdownAction.length());
  9. } else {
  10. reason = null;
  11. }
  12. // If it's a pending reboot into recovery to apply an update,
  13. // always make sure uncrypt gets executed properly when needed.
  14. // If '/cache/recovery/block.map' hasn't been created, stop the
  15. // reboot which will fail for sure, and get a chance to capture a
  16. // bugreport when that's still feasible. (Bug: 26444951)
  17. if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
  18. File packageFile = new File(UNCRYPT_PACKAGE_FILE);
  19. if (packageFile.exists()) {
  20. String filename = null;
  21. try {
  22. filename = FileUtils.readTextFile(packageFile, 0, null);
  23. } catch (IOException e) {
  24. Slog.e(TAG, "Error reading uncrypt package file", e);
  25. }
  26. if (filename != null && filename.startsWith("/data")) {
  27. if (!new File(BLOCK_MAP_FILE).exists()) {
  28. Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
  29. "unexpected runtime restart?");
  30. return;
  31. }
  32. }
  33. }
  34. }
  35. ShutdownThread.rebootOrShutdown(null, reboot, reason);
  36. }
  37. }

依据注释,和代码名,最近一次关机操作(启动SystemServer是在开机过程中),是非正常状态,该代码将shutdown操作悬挂.(想要明白此处还要明白android的关机流程,还要努力!!!).


  1. // Initialize the system context.
  2. createSystemContext();

看看createSystemContext()做了什么

  1. private void createSystemContext() {
  2. ActivityThread activityThread = ActivityThread.systemMain();
  3. mSystemContext = activityThread.getSystemContext();
  4. mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
  5. final Context systemUiContext = activityThread.getSystemUiContext();
  6. systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
  7. }

这里还是通过ActivityThread.java来操作,和启动一个应用进程类似,只不过应用进程是使用ActivityThread.java->main(),这里是使用ActivityThread.java->systemMain();这两者一定有区别,因为普通进程是要attach到AMS的,这里AMS还没有出生…可以对比ActivityThread.java里面的代码进行分析,对比.为了不偏离主线,这里就不深入分析了.接着往下看:


  1. // Create the system service manager.
  2. mSystemServiceManager = new SystemServiceManager(mSystemContext);
  3. mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
  4. LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
  5. // Prepare the thread pool for init tasks that can be parallelized
  6. SystemServerInitThreadPool.get();

启动AMS\PMS\WMS等等这些系统级的服务前,要把管理他们的服务SystemServiceManager启动起来吧,老铁,这没有问题吧~~~LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);将SystemServiceManager对象保存SystemServer进程中的一个数据结构中.SystemServerInitThreadPool.get();初始化线程池,为了初始化任务能够并行处理.这些启动系统级服务的准备工作都做好了,是不是该启动服务了:

  1. // Start services.
  2. try {
  3. traceBeginAndSlog("StartServices");
  4. startBootstrapServices();
  5. startCoreServices();
  6. startOtherServices();
  7. SystemServerInitThreadPool.shutdown();
  8. } catch (Throwable ex) {
  9. Slog.e("System", "******************************************");
  10. Slog.e("System", "************ Failure starting system services", ex);
  11. throw ex;
  12. } finally {
  13. traceEnd();
  14. }

终于到启动这些重量级的系统级的服务了,通过startBootstrapServices()主要用于启动系统Boot级服务 ,startCoreServices()主要用于启动系统核心的服务,startOtherServices()主要用于启动一些非紧要或者是非需要及时启动的服务.启动完成之后使用SystemServerInitThreadPool.shutdown()讲线程池关闭.接着我们注意分析startBootstrapServices(),startCoreServices(),startOtherServices()这三个函数.
首先看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. ......
  10. Installer installer = mSystemServiceManager.startService(Installer.class);
  11. traceEnd();
  12. ......
  13. // In some cases after launching an app we need to access device identifiers,
  14. // therefore register the device identifier policy before the activity manager.
  15. traceBeginAndSlog("DeviceIdentifiersPolicyService");
  16. mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
  17. traceEnd();
  18. // Activity manager runs the show.
  19. traceBeginAndSlog("StartActivityManager");
  20. mActivityManagerService = mSystemServiceManager.startService(
  21. ActivityManagerService.Lifecycle.class).getService();
  22. mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  23. mActivityManagerService.setInstaller(installer);
  24. traceEnd();
  25. // Power manager needs to be started early because other services need it.
  26. // Native daemons may be watching for it to be registered so it must be ready
  27. // to handle incoming binder calls immediately (including being able to verify
  28. // the permissions for those calls).
  29. traceBeginAndSlog("StartPowerManager");
  30. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
  31. traceEnd();
  32. // Now that the power manager has been started, let the activity manager
  33. // initialize power management features.
  34. traceBeginAndSlog("InitPowerManagement");
  35. mActivityManagerService.initPowerManagement();
  36. traceEnd();
  37. // Bring up recovery system in case a rescue party needs a reboot
  38. if (!SystemProperties.getBoolean("config.disable_noncore", false)) {
  39. traceBeginAndSlog("StartRecoverySystemService");
  40. mSystemServiceManager.startService(RecoverySystemService.class);
  41. traceEnd();
  42. }
  43. // Now that we have the bare essentials of the OS up and running, take
  44. // note that we just booted, which might send out a rescue party if
  45. // we're stuck in a runtime restart loop.
  46. RescueParty.noteBoot(mSystemContext);
  47. // Manages LEDs and display backlight so we need it to bring up the display.
  48. traceBeginAndSlog("StartLightsService");
  49. mSystemServiceManager.startService(LightsService.class);
  50. traceEnd();
  51. // Display manager is needed to provide display metrics before package manager
  52. // starts up.
  53. traceBeginAndSlog("StartDisplayManager");
  54. mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
  55. traceEnd();
  56. // We need the default display before we can initialize the package manager.
  57. traceBeginAndSlog("WaitForDisplay");
  58. mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
  59. traceEnd();
  60. // Only run "core" apps if we're encrypting the device.
  61. String cryptState = SystemProperties.get("vold.decrypt");
  62. if (ENCRYPTING_STATE.equals(cryptState)) {
  63. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  64. mOnlyCore = true;
  65. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  66. Slog.w(TAG, "Device encrypted - only parsing core apps");
  67. mOnlyCore = true;
  68. }
  69. // Start the package manager.
  70. if (!mRuntimeRestart) {
  71. MetricsLogger.histogram(null, "boot_package_manager_init_start",
  72. (int) SystemClock.elapsedRealtime());
  73. }
  74. traceBeginAndSlog("StartPackageManagerService");
  75. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  76. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  77. mFirstBoot = mPackageManagerService.isFirstBoot();
  78. mPackageManager = mSystemContext.getPackageManager();
  79. traceEnd();
  80. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  81. MetricsLogger.histogram(null, "boot_package_manager_init_ready",
  82. (int) SystemClock.elapsedRealtime());
  83. }
  84. // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
  85. // A/B artifacts after boot, before anything else might touch/need them.
  86. // Note: this isn't needed during decryption (we don't have /data anyways).
  87. if (!mOnlyCore) {
  88. boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
  89. false);
  90. if (!disableOtaDexopt) {
  91. traceBeginAndSlog("StartOtaDexOptService");
  92. try {
  93. OtaDexoptService.main(mSystemContext, mPackageManagerService);
  94. } catch (Throwable e) {
  95. reportWtf("starting OtaDexOptService", e);
  96. } finally {
  97. traceEnd();
  98. }
  99. }
  100. }
  101. traceBeginAndSlog("StartUserManagerService");
  102. mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
  103. traceEnd();
  104. // Initialize attribute cache used to cache resources from packages.
  105. traceBeginAndSlog("InitAttributerCache");
  106. AttributeCache.init(mSystemContext);
  107. traceEnd();
  108. // Set up the Application instance for the system process and get started.
  109. traceBeginAndSlog("SetSystemProcess");
  110. mActivityManagerService.setSystemProcess();
  111. traceEnd();
  112. // DisplayManagerService needs to setup android.display scheduling related policies
  113. // since setSystemProcess() would have overridden policies due to setProcessGroup
  114. mDisplayManagerService.setupSchedulerPolicies();
  115. /// M: CTA requirement - permission control @{
  116. /// M: MOTA for CTA permissions handling
  117. /*
  118. * This function is used for granting CTA permissions after OTA upgrade.
  119. * This should be placed after AMS is added to ServiceManager and before
  120. * starting other services since granting permissions needs AMS instance
  121. * to do permission checking.
  122. */
  123. mPackageManagerService.onAmsAddedtoServiceMgr();
  124. /// @}
  125. // Manages Overlay packages
  126. traceBeginAndSlog("StartOverlayManagerService");
  127. mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
  128. traceEnd();
  129. // The sensor service needs access to package manager service, app ops
  130. // service, and permissions service, therefore we start it after them.
  131. // Start sensor service in a separate thread. Completion should be checked
  132. // before using it.
  133. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
  134. BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
  135. SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
  136. traceLog.traceBegin(START_SENSOR_SERVICE);
  137. startSensorService();
  138. traceLog.traceEnd();
  139. }, START_SENSOR_SERVICE);
  140. }

首先分析

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

mSystemServiceManager是系统服务管理对象,在前面介绍的run()里面已经实例化了.这里简单介绍一下Installer类,该类是系统安装apk时的一个服务类,继承SystemService(系统服务的一个抽象接口),我们需要在启动完成Installer服务之后才能启动其他的系统服务.接着可以看到ActivityManagerService,PowerManagerService,RecoverySystemService,LightsService,DisplayManagerService,UserManagerService这些服务都是使用mSystemServiceManager.startService()方法将服务启动起来.
发现PackageManagerService服务和其他的有点不一样,他是直接调用了静态方法main()方法实现了

  1. // Start the package manager.
  2. if (!mRuntimeRestart) {
  3. MetricsLogger.histogram(null, "boot_package_manager_init_start",
  4. (int) SystemClock.elapsedRealtime());
  5. }
  6. traceBeginAndSlog("StartPackageManagerService");
  7. mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
  8. mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
  9. //mFirstBoot是判断是否第一次开机的标示,isFirstBoot()是对应的方法,原理就是判断packages.xml是否存在
  10. mFirstBoot = mPackageManagerService.isFirstBoot();
  11. mPackageManager = mSystemContext.getPackageManager();
  12. traceEnd();
  13. if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
  14. MetricsLogger.histogram(null, "boot_package_manager_init_ready",
  15. (int) SystemClock.elapsedRealtime());
  16. }

分析main()函数:

  1. public static PackageManagerService main(Context context, Installer installer,
  2. boolean factoryTest, boolean onlyCore) {
  3. // Self-check for initial settings.
  4. PackageManagerServiceCompilerMapping.checkProperties();
  5. PackageManagerService m = new PackageManagerService(context, installer,
  6. factoryTest, onlyCore);
  7. m.enableSystemUserPackages();
  8. ServiceManager.addService("package", m);
  9. return m;
  10. }

这里是直接newPackageManagerService,然后调用ServiceManager.addService,通过了binder(以后再仔细研究). 这里有一段涉及vold服务的:

  1. // Only run "core" apps if we're encrypting the device.
  2. String cryptState = SystemProperties.get("vold.decrypt");
  3. if (ENCRYPTING_STATE.equals(cryptState)) {
  4. Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
  5. mOnlyCore = true;
  6. } else if (ENCRYPTED_STATE.equals(cryptState)) {
  7. Slog.w(TAG, "Device encrypted - only parsing core apps");
  8. mOnlyCore = true;
  9. }

android 4.0新增的一个功能,即设备加密(encrypting the device),该功能由系统属性vold.decrypt指定.涉及设备安全和加密的,vold(Volume Daemon)用于管理和控制Android平台外部存储设备的后台进程,这些管理和控制,包括SD卡的插拔事件检测、SD卡挂载、卸载、格式化等。这里的设置是当我们的设备处于加密状态,只启动核心服务,通过设置mOnlyCore来进行标示. 接着分析startCoreServices()函数:

  1. /**
  2. * Starts some essential services that are not tangled up in the bootstrap process.
  3. */
  4. private void startCoreServices() {
  5. // Records errors and logs, for example wtf()
  6. traceBeginAndSlog("StartDropBoxManager");
  7. mSystemServiceManager.startService(DropBoxManagerService.class);
  8. traceEnd();
  9. traceBeginAndSlog("StartBatteryService");
  10. // Tracks the battery level. Requires LightService.
  11. mSystemServiceManager.startService(BatteryService.class);
  12. traceEnd();
  13. // Tracks application usage stats.
  14. traceBeginAndSlog("StartUsageService");
  15. mSystemServiceManager.startService(UsageStatsService.class);
  16. mActivityManagerService.setUsageStatsManager(
  17. LocalServices.getService(UsageStatsManagerInternal.class));
  18. traceEnd();
  19. // Tracks whether the updatable WebView is in a ready state and watches for update installs.
  20. traceBeginAndSlog("StartWebViewUpdateService");
  21. mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
  22. traceEnd();
  23. }

启动了DropBoxManagerService(系统出问题的调用栈信息),BatteryService(电池相关的服务),UsageStatsService,WebViewUpdateService.
startOtherServices方法,主要用于启动系统中其他的服务,包括Luncher的启动

总结

  • SystemServer进程是android中一个很重要的进程由Zygote进程启动,是Zygote的嫡长子,如果该进程崩溃,Zygote会调用方法kill掉自己;
  • SystemServer进程主要用于启动系统中的服务;
  • SystemServer进程启动服务的启动函数为main函数,其实真正干活的还是在run()方法里面;
  • SystemServer在执行过程中首先会初始化一些系统变量,加载类库,创建Context对象,创建SystemServiceManager对象等之后才开始启动系统服务;
  • SystemServer进程将系统服务分为三类:boot服务,core服务和other服务,并逐步启动;
  • SertemServer进程在尝试启动服务之前会首先尝试与Zygote建立socket通讯,只有通讯成功之后才会开始尝试启动服务;
  • 创建的系统服务过程中主要通过SystemServiceManager对象来管理,通过调用服务对象的构造方法和onStart方法初始化服务的相关变量;
  • 服务对象都有自己的异步消息对象,并运行在单独的线程中;

参考文章:
http://blog.csdn.net/qq_23547831/article/details/51105171