参考:
https://blog.csdn.net/xichangbao/article/details/53104810
https://blog.csdn.net/wjky2014/article/details/100942423
https://blog.csdn.net/TQLSDLWSL/article/details/121291966
https://www.jianshu.com/p/9912a556734f
https://xiaozhuanlan.com/topic/3068175429
https://www.jianshu.com/p/233507e0564d
前文:
http://www.gaohaiyan.com/4093.html
frameworks/base/services/java/com/android/server/SystemServer.java
1. 入口main()
上一篇梳理到,ZygoteInit.zygoteInit --> RuntimeInit.applicationInit 返回的是一个Runnable,其中记录了反射SystemServer的信息,启动时会执行main方法。
1 2 3 4 5 |
/** 416行 * The main entry point from zygote. */ public static void main(String[] args) { new SystemServer().run(); // 【--- 2,3 ---】 } |
2. SystemServer构造方法
记录几个开始运行的时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 420行 public SystemServer() { // Check for factory test mode. mFactoryTestMode = FactoryTest.getMode(); // Record process start information. 记录过程开始信息。注意 FDE设备完全引导时,SYSPROP_START_COUNT计数将增加2; // Note SYSPROP_START_COUNT will increment by *2* on a FDE device when it fully boots;(Full Disk Encryption(FDE)全盘加密) // one for the password screen, second for the actual boot.一个用于密码屏幕,另一个用于实际引导。 mStartCount = SystemProperties.getInt(SYSPROP_START_COUNT, 0) + 1; mRuntimeStartElapsedTime = SystemClock.elapsedRealtime(); mRuntimeStartUptime = SystemClock.uptimeMillis(); Process.setStartTimes(mRuntimeStartElapsedTime, mRuntimeStartUptime); // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot We don't use "mStartCount > 1" here because it'll be wrong on a FDE device. // TODO: mRuntimeRestart will *not* be set to true if the proccess crashes before sys.boot_completed is set. Fix it. // 如果是运行时重新(当sys.boot_completed已经设置好时)或直接重启,我们在这里不使用“mStartCount>1”,因为这在FDE设备上是错误的。 // todo:如果在设置sys.boot_completed之前,进程崩溃,那么mRuntimeRestart将不会设置为true。修复它。 mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed")); } |
3. 开始启动各个服务run()
配置一些基本属性和资源,逐个启动服务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
// 438行 private void run() { TimingsTraceAndSlog t = new TimingsTraceAndSlog(); try { t.traceBegin("InitBeforeStartServices"); // Record the process start information in sys props. 在sys props中记录流程启动信息。 SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount)); SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime)); SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime)); EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START, mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime); // Default the timezone property to GMT if not set. 如果未设置,则将时区属性默认为GMT(格林尼治标准时间)。 String timezoneProperty = SystemProperties.get("persist.sys.timezone"); if (timezoneProperty == null || timezoneProperty.isEmpty()) { Slog.w(TAG, "Timezone not set; setting to GMT."); SystemProperties.set("persist.sys.timezone", "GMT"); } // If the system has "persist.sys.language" and friends set, replace them with "persist.sys.locale". // 如果系统设置了“persist.sys.language”属性并可用,将其替换为“persist.sys.locale”。 // Note that the default locale at this point is calculated using the "-Duser.locale" command line flag. // 请注意,此时的默认语言环境是使用“-Duser.locale”命令行标志计算的。 // That flag is usually populated by AndroidRuntime using the same set of system properties, // 该标志通常由AndroidRuntime使用相同的系统属性集填充, // but only the system_server and system apps are allowed to set them. // 但仅允许system\u服务器和系统应用程序进行设置。 // NOTE: Most changes made here will need an equivalent change to core/jni/AndroidRuntime.cpp // 这里所做的大多数更改都需要改写 core/jni/AndroidRuntime.cpp if (!SystemProperties.get("persist.sys.language").isEmpty()) { final String languageTag = Locale.getDefault().toLanguageTag(); SystemProperties.set("persist.sys.locale", languageTag); SystemProperties.set("persist.sys.language", ""); SystemProperties.set("persist.sys.country", ""); SystemProperties.set("persist.sys.localevar", ""); } // The system server should never make non-oneway calls 系统服务器不应进行非单向调用 Binder.setWarnOnBlocking(true); // The system server should always load safe labels 系统服务器应始终加载安全标签 PackageItemInfo.forceSafeLabels(); // Default to FULL within the system server. 系统服务器中的默认值为FULL。 SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL; // Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized 在初始化设置提供程序之前,停用SQLITeCompatibilityWallags SQLiteCompatibilityWalFlags.init(null); // Here we go! 进入安卓的SystemServer Slog.i(TAG, "Entered the Android system server!"); final long uptimeMillis = SystemClock.elapsedRealtime(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis); if (!mRuntimeRestart) { FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_INIT_START, uptimeMillis); } // In case the runtime switched since last boot (such as when the old runtime was removed in an OTA), set the system property so that it is in sync. // We can't do this in libnativehelper's JniInvocation::Init code where we already had to fallback to a different runtime // because it is running as root and we need to be the system user to set the property. http://b/11463182 // 如果自上次启动后运行时发生切换(例如在OTA中删除旧运行时),设置系统属性,使其同步。 // 在libnativehelper的JniInvocation::Init代码中,我们无法做到这一点,因为我们必须回退到另一个运行时。因为它是以root用户身份运行的,我们需要是系统用户才能设置属性。 // libcore/libart/src/main/java/dalvik/system/VMRuntime.java,199行public static VMRuntime getRuntime(),229行,public native String vmLibrary()。 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // 虚拟机库文件路径。返回提供VM实现的共享库的名称。 // Mmmmmm... more memory! 清理内存上限。删除任何增长限制,允许应用程序分配最大堆大小。 VMRuntime.getRuntime().clearGrowthLimit(); // VMRuntime.java,1483行 // frameworks/base/core/java/android/os/Build.java // Some devices rely on runtime fingerprint generation, so make sure we've defined it before booting further. Build.ensureFingerprintProperty(); // 一些设备依赖于运行时指纹生成,因此请确保在进一步引导之前定义了[指纹生成]。 // Within the system server, it is an error to access Environment paths without explicitly specifying a user. Environment.setUserRequired(true); // 在系统服务器中,在没有明确指定用户的情况下访问环境路径是错误的。 // Within the system server, any incoming Bundles should be defused to avoid throwing BadParcelableException. BaseBundle.setShouldDefuse(true); // 在系统服务器中,应解除任何传入的捆绑包,以避免引发BadParcelableException。 // Within the system server, when parceling exceptions, include the stack trace Parcel.setStackTraceParceling(true); // 在系统服务器中,当包裹异常时,包括堆栈跟踪 // Ensure binder calls into the system always run at foreground priority. BinderInternal.disableBackgroundScheduling(true); // 确保进入系统的binder始终在前台优先级运行。 // Increase the number of binder threads in system_server BinderInternal.setMaxThreads(sMaxBinderThreads); // 增加system_server中binder线程池的最大数量 // Prepare the main looper thread (this thread). 准备主函数循环(当前线程)。 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); Looper.prepareMainLooper(); // 将当前线程初始化并标记为应用程序的主循环器。frameworks/base/core/java/android/os/Looper.java,约122行。 Looper.getMainLooper() // 拿到循环器。约135行。 .setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // 约341行。为慢速调度/传递日志设置阈值。 SystemServiceRegistry.sEnableServiceNotFoundWtf = true; // Initialize native services. 初始化本地服务。 System.loadLibrary("android_servers"); // Allow heap / perf profiling. 允许堆/性能分析。 initZygoteChildHeapProfiling(); // native方法。 // Debug builds - spawn a thread to monitor for fd leaks. 调试构建-生成一个线程以监视fd泄漏。 if (Build.IS_DEBUGGABLE) { spawnFdLeakCheckThread(); // native方法,生成一个监视fd泄漏的线程。 } // Check whether we failed to shut down last time we tried. This call may not return. performPendingShutdown(); // 644行。检查上次尝试时是否未能关闭。此呼叫可能不会返回。 // Initialize the system context. 初始化系统上下文。 createSystemContext(); // 697行。通过ActivityThread,拿到mSystemContext 【--- 3.1 ---】 // Call per-process mainline module initialization. ActivityThread.initializeMainlineModules(); // 按进程调用主线模块初始化。 // Create the system service manager. frameworks/base/services/core/java/com/android/server/SystemServiceManager.java mSystemServiceManager = new SystemServiceManager(mSystemContext); // 创建系统服务管理器 mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // 一个Map<Class, Object>。frameworks/base/core/java/com/android/server/LocalServices.java // Prepare the thread pool for init tasks that can be parallelized。frameworks/base/services/core/java/com/android/server/SystemServerInitThreadPool.java,126行。 SystemServerInitThreadPool.start(); // 为可以并行化的初始化任务准备线程池 // Attach JVMTI agent if this is a debuggable build and the system property is set. if (Build.IS_DEBUGGABLE) { // 如果这是一个可调试的生成,并且设置了系统属性,就附加JVMTI代理。 // Property is of the form "library_path=parameters". String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent"); if (!jvmtiAgent.isEmpty()) { int equalIndex = jvmtiAgent.indexOf('='); String libraryPath = jvmtiAgent.substring(0, equalIndex); String parameterList = jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length()); // Attach the agent. try { Debug.attachJvmtiAgent(libraryPath, parameterList, null); } catch (Exception e) { Slog.e("System", "*************************************************"); Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent); } } } } finally { t.traceEnd(); // InitBeforeStartServices } // Setup the default WTF handler。frameworks/base/core/java/com/android/internal/os/RuntimeInit.java RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf); // 约482行。设置默认WTF处理程序 // Start services. 启动各个服务 try { t.traceBegin("StartServices"); startBootstrapServices(t); // 713行。【--- 4 ---】运行启动系统过程中所须的一小部分关键服务。系统引导服务。 startCoreServices(t); // 956行。【--- 5 ---】启动一些硬件相关的基本服务。系统核心服务。 startOtherServices(t); // 1019行。【--- 6 ---】启动framework层的服务。应用相关服务。 } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { t.traceEnd(); // StartServices } // frameworks/base/core/java/android/os/StrictMode.java StrictMode.initVmDefaults(null); // 约1424行。初始化严格模式的VM默认方案 if (!mRuntimeRestart && !isFirstBootOrUpgrade()/*约635行,新机首次开机或系统升级*/) { final long uptimeMillis = SystemClock.elapsedRealtime(); FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY, uptimeMillis); final long maxUptimeMillis = 60 * 1000; if (uptimeMillis > maxUptimeMillis) { Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis); } } // Diagnostic to ensure that the system is in a base healthy state. Done here as a common non-zygote process. if (!VMRuntime.hasBootImageSpaces()) { // VMRuntime.java,702行。诊断以确保系统处于基本健康状态。作为一种常见的非zygote进程在这里完成。 Slog.wtf(TAG, "Runtime is not running with a boot image!"); } // Loop forever. Looper.loop(); // 约154行。在此线程中运行消息队列。一定要打电话 {@link#quit()}结束循环。 throw new RuntimeException("Main thread loop unexpectedly exited"); } // end run |
3.1. createSystemContext
调用ActivityThread提取上下文。
1 2 3 4 5 6 7 8 9 10 |
// 697行。拿到系统上下文 private void createSystemContext() { // frameworks/base/core/java/android/app/ActivityThread.java ActivityThread activityThread = ActivityThread.systemMain(); // 约7417行。public static ActivityThread systemMain() mSystemContext = activityThread.getSystemContext(); // 约2447行。public ContextImpl getSystemContext() mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); final Context systemUiContext = activityThread.getSystemUiContext(); systemUiContext.setTheme(DEFAULT_SYSTEM_THEME); } |
4. startBootstrapServices
运行启动系统过程中所须的一小部分关键服务。系统引导服务。二十来个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
/** 713行 * Starts the small tangle of critical services that are needed to get the system off the ground. * These services have complex mutual dependencies which is why we initialize them all in one place here. * Unless your service is also entwined in these dependencies, it should be initialized in one of the other functions. * 启动启动系统所需的一小部分关键服务,它们具有复杂的相互依赖性,除非您的服务也纠缠在这些依赖项中,否则应该在其他函数中对其进行初始化。 */ private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) { t.traceBegin("startBootstrapServices"); // Start the watchdog as early as possible so we can crash the system server if we deadlock during early boot t.traceBegin("StartWatchdog"); // 尽早启动看门狗,以便在早期引导期间出现死锁时使系统服务器崩溃 final Watchdog watchdog = Watchdog.getInstance(); watchdog.start(); t.traceEnd(); Slog.i(TAG, "Reading configuration..."); final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig"; t.traceBegin(TAG_SYSTEM_CONFIG); // frameworks/base/core/java/com/android/server/SystemConfig.java,约241行。 SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG); // SystemServerInitThreadPool.java,76行。 t.traceEnd(); // [平台兼容服务]由AMS、PMS以及将来可能的其他服务使用。 // Platform compat service is used by ActivityManagerService, PackageManagerService, and possibly others in the future. b/135010838. t.traceBegin("PlatformCompat"); PlatformCompat platformCompat = new PlatformCompat(mSystemContext); // frameworks/base/services/core/java/com/android/server/compat/PlatformCompat.java // 在ServiceManager中注册的是封装到一个Binder类中用于其它进程调用的接口。frameworks/base/core/java/android/os/ServiceManager.java,约165行。 ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat); // "platform_compat",frameworks/base/core/java/android/content/Context.java ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE, new PlatformCompatNative(platformCompat)); // "platform_compat_native" AppCompatCallbacks.install(new long[0]); t.traceEnd(); // FileIntegrityService responds to requests from apps and the system. It needs to run after the source (i.e. keystore) is ready, // and before the apps (or the first customer in the system) run. // FileIntegrityService响应来自应用程序和系统的请求。它需要在源准备就绪后及应用程序(或系统中的第一个客户)运行之前运行, t.traceBegin("StartFileIntegrityService"); // SystemServiceManager.java,约86行。startService(String className) mSystemServiceManager.startService(FileIntegrityService.class); // 文件完整性服务 t.traceEnd(); // Wait for installd to finish starting up so that it has a chance to create critical directories such as /data/user with the appropriate permissions. // We need this to complete before we initialize other services. // 等待installd完成启动,以便它有机会创建具有适当权限的关键目录,如/data/user。我们需要在初始化其它服务之前完成此操作。 t.traceBegin("StartInstaller"); // frameworks/base/services/core/java/com/android/server/pm/Installer.java Installer installer = mSystemServiceManager.startService(Installer.class); // PMS所依赖的关键系统服务,也是安装应用的实际执行者 t.traceEnd(); // In some cases after launching an app we need to access device identifiers, // therefore register the device identifier policy before the activity manager. // 在某些情况下,启动应用程序后,我们需要访问设备标识符,因此,请在活动管理器之前注册设备标识符策略。 t.traceBegin("DeviceIdentifiersPolicyService"); mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class); // 设备标识符策略服务 t.traceEnd(); // Uri Grants Manager. Uri授权管理器。 t.traceBegin("UriGrantsManagerService"); mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class); // Uri授权管理器服务 t.traceEnd(); // Activity manager runs the show. 启动Activity管理器-AMS t.traceBegin("StartActivityManager"); // TODO: Might need to move after migration to WM. todo:迁移到WindowManamger。 ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService(); // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java,2340行。 mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm); // ATMS是Android10新增,接替部分AMS工作。 mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); t.traceEnd(); // Data loader manager service needs to be started before package manager // 需要在包管理器之前启动Data loader manager服务 t.traceBegin("StartDataLoaderManagerService"); mDataLoaderManagerService = mSystemServiceManager.startService(DataLoaderManagerService.class); // 数据加载器管理器服务 t.traceEnd(); // Incremental service needs to be started before package manager // 需要在包管理器之前启动增量服务 t.traceBegin("StartIncrementalService"); mIncrementalServiceHandle = startIncrementalService(); // native方法。启动增量服务 t.traceEnd(); // Power manager needs to be started early because other services need it. // Native daemons may be watching for it to be registered so it must be ready to handle incoming binder calls immediately // (including being able to verify the permissions for those calls). // 需要尽早启动电源管理,因为其它服务需要它。本机守护进程可能正在监视它的注册,因此它必须准备好立即处理传入的绑定器调用(包括能够验证这些调用的权限)。 t.traceBegin("StartPowerManager"); mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); // 电源管理服务 t.traceEnd(); t.traceBegin("StartThermalManager"); mSystemServiceManager.startService(ThermalManagerService.class); // 温控管理服务 t.traceEnd(); // Now that the power manager has been started, let the activity manager initialize power management features. // 现在电源管理器已经启动,让活动管理器初始化电源管理功能。 t.traceBegin("InitPowerManagement"); mActivityManagerService.initPowerManagement(); // ActivityManagerService.java,2751行。BatteryStatsService电源管理服务 t.traceEnd(); // Bring up recovery system in case a rescue party needs a reboot // 启动恢复系统,以防系统恢复功能需要重新启动 t.traceBegin("StartRecoverySystemService"); mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class); // 系统升级服务 t.traceEnd(); // Now that we have the bare essentials of the OS up and running, take note that we just booted, // which might send out a rescue party if we're stuck in a runtime restart loop. // 现在已经安装并运行了操作系统的基本要素,请注意,我们刚刚启动,如果我们陷入运行时重启循环,这可能会派出救援队。 RescueParty.registerHealthObserver(mSystemContext); PackageWatchdog.getInstance(mSystemContext).noteBoot(); // Manages LEDs and display backlight so we need it to bring up the display. 管理LED和显示器背光,因此我们需要它来显示显示器。 t.traceBegin("StartLightsService"); mSystemServiceManager.startService(LightsService.class); // 灯光服务。https://www.jianshu.com/p/28e5bdf03ee3 t.traceEnd(); t.traceBegin("StartSidekickService"); // Package manager isn't started yet; need to use SysProp not hardware feature // 包管理器尚未启动;需要使用SysProp去启动而不是硬件功能 if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) { mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS); // 时钟伴侣?"com.google.android.clockwork.sidekick.SidekickService" } t.traceEnd(); // Display manager is needed to provide display metrics before package manager starts up. // 需要显示管理器在包管理器启动之前提供显示度量。 t.traceBegin("StartDisplayManager"); mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); // 全局显示状态管理 t.traceEnd(); // We need the default display before we can initialize the package manager. // 在初始化包管理器之前,我们需要默认显示。 t.traceBegin("WaitForDisplay"); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); // SystemServiceManager.java,193行。通知现有服务:“系统启动到了xxx阶段,你们各自进行下一步” t.traceEnd(); // Only run "core" apps if we're encrypting the device. 只有在加密设备时才运行“核心”应用程序。 String cryptState = VoldProperties.decrypt().orElse(""); if (ENCRYPTING_STATE.equals(cryptState)) { Slog.w(TAG, "Detected encryption in progress - only parsing core apps"); mOnlyCore = true; } else if (ENCRYPTED_STATE.equals(cryptState)) { Slog.w(TAG, "Device encrypted - only parsing core apps"); mOnlyCore = true; } // Start the package manager. 启动包管理器 if (!mRuntimeRestart) { FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START, SystemClock.elapsedRealtime()); } t.traceBegin("StartPackageManagerService"); try { Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain"); // frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java,2592行。 mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); // PMS/PKMS包管理器服务 } finally { Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain"); } // Now that the package manager has started, register the dex load reporter to capture any dex files loaded by system server. // These dex files will be optimized by the BackgroundDexOptService. // 现在包管理器已经启动,注册dex文件加载的通讯器,以捕获系统服务器加载的任何dex文件。这些dex文件将由BackgroundDexOptService进行优化。 SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); t.traceEnd(); if (!mRuntimeRestart && !isFirstBootOrUpgrade()) { FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED, FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY, SystemClock.elapsedRealtime()); } // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename A/B artifacts after boot, // before anything else might touch/need them. Note: this isn't needed during decryption (we don't have /data anyways). // 管理器的A/B OTA选择。这个引导服务启动后,要在其它任何东西可能触及/需要它们之前,重命名。注意:解密过程中不需要这样做(我们没有/数据)。 if (!mOnlyCore) { boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false); if (!disableOtaDexopt) { t.traceBegin("StartOtaDexOptService"); try { Watchdog.getInstance().pauseWatchingCurrentThread("moveab"); OtaDexoptService.main(mSystemContext, mPackageManagerService); } catch (Throwable e) { reportWtf("starting OtaDexOptService", e); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("moveab"); t.traceEnd(); } } } t.traceBegin("StartUserManagerService"); mSystemServiceManager.startService(UserManagerService.LifeCycle.class); // 用户管理服务 t.traceEnd(); // Initialize attribute cache used to cache resources from packages. 初始化用于缓存包中资源的属性缓存。 t.traceBegin("InitAttributerCache"); AttributeCache.init(mSystemContext); t.traceEnd(); // Set up the Application instance for the system process and get started. 为系统进程设置应用程序实例并开始。 t.traceBegin("SetSystemProcess"); mActivityManagerService.setSystemProcess(); t.traceEnd(); // Complete the watchdog setup with an ActivityManager instance and listen for reboots // Do this only after the ActivityManagerService is properly started as a system process // 使用ActivityManager实例完成看门狗设置,并侦听是否重新启动。只有在ActivityManagerService作为系统进程正确启动后才能执行此操作 t.traceBegin("InitWatchdog"); watchdog.init(mSystemContext, mActivityManagerService); t.traceEnd(); // DisplayManagerService needs to setup android.display scheduling related policies // since setSystemProcess() would have overridden policies due to setProcessGroup // DisplayManagerService需要设置android。显示与计划相关的策略,因为setSystemProcess()会由于setProcessGroup而重写策略 mDisplayManagerService.setupSchedulerPolicies(); // Manages Overlay packages。管理覆盖包 t.traceBegin("StartOverlayManagerService"); mSystemServiceManager.startService(new OverlayManagerService(mSystemContext)); // 资源管理框架之OMS,能够在运行时动态替换res。http://www.javashuo.com/article/p-mhiouqnn-mu.html t.traceEnd(); t.traceBegin("StartSensorPrivacyService"); mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext)); // 傳感器服务 t.traceEnd(); if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) { // DisplayManager needs the overlay immediately. DisplayManager需要立即覆盖。 mActivityManagerService.updateSystemUiContext(); LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged(); } // The sensor service needs access to package manager service, app ops service, and permissions service, // therefore we start it after them. Start sensor service in a separate thread. Completion should be checked before using it. // 传感器服务需要访问PackageManagerService、AppOpsService和PermissionsService,因此,它们之后在单独的线程中启动传感器服务。使用前应检查是否完整。 mSensorServiceStart = SystemServerInitThreadPool.submit(() -> { TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(START_SENSOR_SERVICE); startSensorService(); // native方法 traceLog.traceEnd(); }, START_SENSOR_SERVICE); t.traceEnd(); // startBootstrapServices } // end startBootstrapServices |
5. startCoreServices
启动一些硬件相关的基本服务。系统核心服务。十个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
/** 956行 * Starts some essential services that are not tangled up in the bootstrap process. * 启动一些在引导过程中没有混乱的基本服务。 */ private void startCoreServices(@NonNull TimingsTraceAndSlog t) { t.traceBegin("startCoreServices"); // Service for system config 系统配置服务 t.traceBegin("StartSystemConfigService"); mSystemServiceManager.startService(SystemConfigService.class); // 系统配置服务 t.traceEnd(); t.traceBegin("StartBatteryService"); // Tracks the battery level. Requires LightService. 跟踪电池电量。需要调用LightService。 mSystemServiceManager.startService(BatteryService.class); // 电池电量管理 t.traceEnd(); // Tracks application usage stats. 跟踪应用程序使用情况统计信息。 t.traceBegin("StartUsageService"); mSystemServiceManager.startService(UsageStatsService.class); // 应用使用统计服务 mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class)); t.traceEnd(); // Tracks whether the updatable WebView is in a ready state and watches for update installs. // 跟踪可更新WebView是否处于就绪状态,并监视更新安装。 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { t.traceBegin("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); // WebView的更新服务 t.traceEnd(); } // Tracks and caches the device state. 跟踪和缓存设备状态。 t.traceBegin("StartCachedDeviceStateService"); mSystemServiceManager.startService(CachedDeviceStateService.class); // 缓存设备状态的服务 t.traceEnd(); // Tracks cpu time spent in binder calls 跟踪binder调用所用的cpu时间 t.traceBegin("StartBinderCallsStatsService"); mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class); // Binder调用状态服务。记录cpu在binder回调中花费的时间 t.traceEnd(); // Tracks time spent in handling messages in handlers. 跟踪处理程序中处理消息所花费的时间。 t.traceBegin("StartLooperStatsService"); mSystemServiceManager.startService(LooperStatsService.Lifecycle.class); // 循环器状态服务。记录使用handler message花费的时间 t.traceEnd(); // Manages apk rollbacks. 管理apk回滚。"com.android.server.rollback.RollbackManagerService" t.traceBegin("StartRollbackManagerService"); mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS); // apk版本降级服务 t.traceEnd(); // Service to capture bugreports. 用于捕获错误报告的服务。 t.traceBegin("StartBugreportManagerService"); mSystemServiceManager.startService(BugreportManagerService.class); // Bug上报管理服务 t.traceEnd(); // Serivce for GPU and GPU driver. GPU和GPU驱动程序服务 t.traceBegin("GpuService"); mSystemServiceManager.startService(GpuService.class); // Gpu管理 t.traceEnd(); t.traceEnd(); // startCoreServices } // end startCoreServices |
6. startOtherServices
启动framework层的服务。应用相关服务。一百四十多个。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 |
/** 1019行 * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized. * 启动一堆杂乱无章的东西,这些东西还没有被重构和组织。 */ private void startOtherServices(@NonNull TimingsTraceAndSlog t) { final Context context = mSystemContext; VibratorService vibrator = null; DynamicSystemService dynamicSystem = null; IStorageManager storageManager = null; NetworkManagementService networkManagement = null; IpSecService ipSecService = null; NetworkStatsService networkStats = null; NetworkPolicyManagerService networkPolicy = null; ConnectivityService connectivity = null; NsdService serviceDiscovery = null; WindowManagerService wm = null; SerialService serial = null; NetworkTimeUpdateService networkTimeUpdater = null; InputManagerService inputManager = null; TelephonyRegistry telephonyRegistry = null; ConsumerIrService consumerIr = null; MmsServiceBroker mmsService = null; HardwarePropertiesManagerService hardwarePropertiesService = null; boolean disableSystemTextClassifier = SystemProperties.getBoolean("config.disable_systemtextclassifier", false); boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false); boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice", false); boolean enableLeftyService = SystemProperties.getBoolean("config.enable_lefty", false); boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1"); boolean isWatch = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH); boolean isArc = context.getPackageManager().hasSystemFeature("org.chromium.arc"); boolean enableVrService = context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE); // For debugging RescueParty 用于调试救援方 if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) { throw new RuntimeException(); } String externalServer = context.getResources().getString(org.lineageos.platform.internal.R.string.config_externalSystemServer); // lineage-sdk/lineage/res/res/values/config.xml:115: <string name="config_externalSystemServer" translatable="false">org.lineageos.platform.internal.LineageSystemServer</string> try { final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload"; // We start the preload ~1s before the webview factory preparation, // to ensure that it completes before the 32 bit relro process is forked from the zygote. // In the event that it takes too long, the webview RELRO process will block, but it will do so without holding any locks. // 我们在webview工厂准备前1s开始预加载,确保它在32位重新定位过程从zygote分叉之前完成。如果需要的时间太长,webview RELRO进程将被阻止,但它不会持有任何锁。 mZygotePreload = SystemServerInitThreadPool.submit(() -> { try { Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD); TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD); if (!Process.ZYGOTE_PROCESS.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) { Slog.e(TAG, "Unable to preload default resources"); } traceLog.traceEnd(); } catch (Exception ex) { Slog.e(TAG, "Exception preloading default resources", ex); } }, SECONDARY_ZYGOTE_PRELOAD); ServiceManager.addService("sec_key_att_app_id_provider", new KeyAttestationApplicationIdProviderService(context)); // 密钥认证应用程序ID提供程序服务 mSystemServiceManager.startService(KeyChainSystemService.class); // 钥匙串服务 ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); // 调度策略 mSystemServiceManager.startService(TelecomLoaderService.class); // 电信加载器服务 telephonyRegistry = new TelephonyRegistry(context, new TelephonyRegistry.ConfigurationProvider()); // 无线通讯 ServiceManager.addService("telephony.registry", telephonyRegistry); mEntropyMixer = new EntropyMixer(context); // 以前的EntropyService,生成随机数 mContentResolver = context.getContentResolver(); // The AccountManager must come before the ContentService AccountManager必须位于ContentService之前 mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS); // 管理"账户",如Email,微博,Facebook账户。"com.android.server.accounts.AccountManagerService$Lifecycle" mSystemServiceManager.startService(CONTENT_SERVICE_CLASS); // 内容服务。"com.android.server.content.ContentService$Lifecycle" mActivityManagerService.installSystemProviders(); // 安装系统Provider。AMS.java,7893行。 // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags 现在设置Provider已经就绪,请重新激活SQLiteCompatibilityWallags SQLiteCompatibilityWalFlags.reset(); // Records errors and logs, for example wtf() Currently this service indirectly depends on SettingsProvider so do this after InstallSystemProviders. // 记录错误和日志,例如wtf(),当前此服务间接依赖于SettingsProvider,所以请在InstallSystemProviders之后执行此操作。 mSystemServiceManager.startService(DropBoxManagerService.class); // 收集各种系统异常日志 vibrator = new VibratorService(context); // 手机震动器服务 ServiceManager.addService("vibrator", vibrator); dynamicSystem = new DynamicSystemService(context); // frameworks/base/services/core/java/com/android/server/DynamicSystemService.java ServiceManager.addService("dynamic_system", dynamicSystem); // 在将请求传递给GSID(群从设备标识符)之前提供权限检查 if (!isWatch) { consumerIr = new ConsumerIrService(context); // CIRS ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); // 红外遥控器控制"consumer_ir" } mSystemServiceManager.startService(new AlarmManagerService(context)); // 声音提示服务 inputManager = new InputManagerService(context); // 输入系统管理。触摸、软件盘、鼠标... // WMS needs sensor service ready. WMS需要传感器服务就绪 ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE); mSensorServiceStart = null; // 窗口管理服务,frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java,1104行。 wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore, new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager); // WMS ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); // "window" ServiceManager.addService(Context.INPUT_SERVICE, inputManager, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); // "input" mActivityManagerService.setWindowManager(wm); // wm.onInitReady(); // Start receiving calls from HIDL services. Start in in a separate thread because it need to connect to SensorManager. // This have to start after START_SENSOR_SERVICE is done. // 开始接收来自HIDL服务的呼叫。在单独的线程中启动,因为它需要连接到SensorManager。这必须在START_SENSOR_SERVICE服务完成后启动。 SystemServerInitThreadPool.submit(() -> { TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(START_HIDL_SERVICES); startHidlServices(); // native方法。启动系统服务器内运行的所有HIDL服务。这可能需要一些时间。 traceLog.traceEnd(); }, START_HIDL_SERVICES); if (!isWatch && enableVrService) { mSystemServiceManager.startService(VrManagerService.class); // 虚拟现实,VR模式管理 } inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback()); // inputManager.start(); // TODO: Use service dependencies instead. todo 改用服务依赖关系。 mDisplayManagerService.windowManagerAndInputReady(); // if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) { Slog.i(TAG, "No Bluetooth Service (factory test)"); } else if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)"); } else { mSystemServiceManager.startService(BluetoothService.class); // 蓝牙服务 } mSystemServiceManager.startService(IpConnectivityMetrics.class); // 核心网络和连接度量的事件缓冲服务。 // https://blog.csdn.net/Vince_/article/details/115178750 《Android 网络管理》 mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class); // 网络监视列表服务 mSystemServiceManager.startService(PinnerService.class); // 页面缓存管理 mSystemServiceManager.startService(IorapForwardingService.class); // iorap转发服务 SignedConfigService.registerUpdateReceiver(mSystemContext); mSystemServiceManager.startService(AppIntegrityManagerService.class); // 应用完整性管理服务 } catch (Throwable e) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting core service"); throw e; } // Before things start rolling, be sure we have decided whether we are in safe mode. // 在事情开始之前,确保我们已经决定是否处于安全模式。 final boolean safeMode = wm.detectSafeMode(); if (safeMode) { // If yes, immediately turn on the global setting for airplane mode. // Note that this does not send broadcasts at this stage because subsystems are not yet up. // We will send broadcasts later to ensure all listeners have the chance to react with special handling. // 如果是,立即打开飞行模式的全局设置。请注意,由于子系统尚未启动,因此此阶段不会发送广播。我们将稍后发送广播,以确保所有听众都有机会作出特殊处理。 Settings.Global.putInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1); } StatusBarManagerService statusBar = null; INotificationManager notification = null; CountryDetectorService countryDetector = null; ILockSettings lockSettings = null; MediaRouterService mediaRouter = null; // Bring up services needed for UI. 启动UI所需的服务。 if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) { mSystemServiceManager.startService(MultiClientInputMethodManagerService.Lifecycle.class); // 多客户端输入法管理服务。https://www.freesion.com/article/8957489234/ } else { mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class); // 输入法管理服务 } try { mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS); // 辅助功能服务。"com.android.server.accessibility.AccessibilityManagerService$Lifecycle" } catch (Throwable e) { reportWtf("starting Accessibility Manager", e); } } try { wm.displayReady(); // WindowManagerService.java,4648行。 } catch (Throwable e) { reportWtf("making display ready", e); } if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) { try { /* NotificationManagerService is dependant on StorageManagerService, NMS依赖于StorageManagerService, * (for media / usb notifications) so we must start StorageManagerService first. */ mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS); // 存储管理。"com.android.server.StorageManagerService$Lifecycle" storageManager = IStorageManager.Stub.asInterface(ServiceManager.getService("mount")); } catch (Throwable e) { reportWtf("starting StorageManagerService", e); } try { mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS); // 磁盘统计服务。"com.android.server.usage.StorageStatsService$Lifecycle" } catch (Throwable e) { reportWtf("starting StorageStatsService", e); } } } // We start this here so that we update our configuration to set watch or television as appropriate. // 我们从这里开始,以便更新配置,以便根据需要设置手表或电视。 mSystemServiceManager.startService(UiModeManagerService.class); // 模式切换服务。夜间模式、行车模式 if (!mOnlyCore) { try { Watchdog.getInstance().pauseWatchingCurrentThread("dexopt"); mPackageManagerService.updatePackagesIfNeeded(); } catch (Throwable e) { reportWtf("update packages", e); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("dexopt"); } } try { mPackageManagerService.performFstrimIfNeeded(); } catch (Throwable e) { reportWtf("performing fstrim", e); } if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { try { mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS); // 锁屏服务。"com.android.server.locksettings.LockSettingsService$Lifecycle" lockSettings = ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings")); } catch (Throwable e) { reportWtf("starting LockSettingsService service", e); } final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals(""); final boolean hasGsi = SystemProperties.getInt(GSI_RUNNING_PROP, 0) > 0; if (hasPdb && !hasGsi) { mSystemServiceManager.startService(PersistentDataBlockService.class); // 持久数据块服务 } mSystemServiceManager.startService(TestHarnessModeService.class); // Android10增加,自动化测试框架服务。https://source.android.google.cn/compatibility/cts/harness if (hasPdb || OemLockService.isHalPresent()) { // Implementation depends on pdb or the OemLock HAL 实施取决于pdb或OemLock HAL mSystemServiceManager.startService(OemLockService.class); // OEM锁。 } mSystemServiceManager.startService(DEVICE_IDLE_CONTROLLER_CLASS); // 设备待机服务 "com.android.server.DeviceIdleController" // Always start the Device Policy Manager, so that the API is compatible with API8. // 始终启动设备策略管理器,以便API与API8兼容。 mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class); // Idle(待机)状态控制。https://blog.csdn.net/kc58236582/article/details/50548318 if (!isWatch) { try { statusBar = new StatusBarManagerService(context); // 状态栏管理服务 ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar); // "statusbar" } catch (Throwable e) { reportWtf("starting StatusBarManagerService", e); } } startContentCaptureService(context, t); // 2510行。内容监听服务。 【--- 6.1 ---】 startAttentionService(context, t); // 2545行。注意力服务。 【--- 6.2 ---】 startSystemCaptionsManagerService(context, t); // 2498行。系统标题管理器服务。【--- 6.3 ---】 // out/soong/.intermediates/frameworks/base/core/res/framework-res/android_common/gen/aapt2/R/com/android/internal/R.java // App prediction manager service 应用程序预测管理器服务 if (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) { mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS); // 近期列表管理服务。"com.android.server.appprediction.AppPredictionManagerService" } else { Slog.d(TAG, "AppPredictionService not defined by OEM"); } // Content suggestions manager service 内容建议管理器服务 if (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService)) { mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS); // 内容建议管理服务。"com.android.server.contentsuggestions.ContentSuggestionsManagerService" } else { Slog.d(TAG, "ContentSuggestionsService not defined by OEM"); } try { ConnectivityModuleConnector.getInstance().init(context); } catch (Throwable e) { reportWtf("initializing ConnectivityModuleConnector", e); } try { NetworkStackClient.getInstance().init(); } catch (Throwable e) { reportWtf("initializing NetworkStackClient", e); } try { networkManagement = NetworkManagementService.create(context); // 网络管理服务 ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement); // "network_management" } catch (Throwable e) { reportWtf("starting NetworkManagement Service", e); } try { ipSecService = IpSecService.create(context, networkManagement); // IP安全性服务 ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService); // "ipsec" } catch (Throwable e) { reportWtf("starting IpSec Service", e); } mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class); // (TSM)为应用程序使用特定文本服务提供环境。这些特定的服务包括拼写检查、复杂文本的输入等 if (!disableSystemTextClassifier) { mSystemServiceManager.startService(TextClassificationManagerService.Lifecycle.class); // 文本分类检索服务 } mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class); // android.net.NetworkScoreManager的备份服务 try { networkStats = NetworkStatsService.create(context, networkManagement); // 网络状态服务 ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats); // "netstats" } catch (Throwable e) { reportWtf("starting NetworkStats Service", e); } try { networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService, networkManagement); // 网络策略管理服务 ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy); // "netpolicy" } catch (Throwable e) { reportWtf("starting NetworkPolicy Service", e); } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) { // Wifi Service must be started first for wifi-related services. Wifi相关服务必须首先启动Wifi服务。 mSystemServiceManager.startServiceFromJar(WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); // WiFi管理。"com.android.server.wifi.WifiService","/apex/com.android.wifi/javalib/service-wifi.jar" mSystemServiceManager.startServiceFromJar(WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); // WIFI扫描服务。"com.android.server.wifi.scanner.WifiScanningService","/apex/com.android.wifi/javalib/service-wifi.jar" } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_RTT)) { mSystemServiceManager.startServiceFromJar(WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); // 往返时间服务,RTT(WiFi Round Trip Time),可用于wlan定位。"com.android.server.wifi.rtt.RttService","/apex/com.android.wifi/javalib/service-wifi.jar" } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE)) { mSystemServiceManager.startServiceFromJar(WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); // WLAN感知,支持多个设备WLAN互联。"com.android.server.wifi.aware.WifiAwareService","/apex/com.android.wifi/javalib/service-wifi.jar" } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) { mSystemServiceManager.startServiceFromJar(WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); // p2p功能服务。"com.android.server.wifi.p2p.WifiP2pService","/apex/com.android.wifi/javalib/service-wifi.jar" } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOWPAN)) { mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS); // 低功率无线个域网服务。"com.android.server.lowpan.LowpanService" } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) { mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS); // 以太网服务。"com.android.server.ethernet.EthernetService" } try { connectivity = new ConnectivityService(context, networkManagement, networkStats, networkPolicy); // 网络连接管理服务 ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL); networkPolicy.bindConnectivityManager(connectivity); } catch (Throwable e) { reportWtf("starting Connectivity Service", e); } try { serviceDiscovery = NsdService.create(context); // Nsd发现服务。Network Service Discovery,⽹络服务发现。扫描局域网内进行了nsd注册的设备 ServiceManager.addService(Context.NSD_SERVICE, serviceDiscovery); } catch (Throwable e) { reportWtf("starting Service Discovery Service", e); } try { ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE, new SystemUpdateManagerService(context)); // 系统升级管理 } catch (Throwable e) { reportWtf("starting SystemUpdateManagerService", e); } try { ServiceManager.addService(Context.UPDATE_LOCK_SERVICE, new UpdateLockService(context)); // 升级锁 } catch (Throwable e) { reportWtf("starting UpdateLockService", e); } mSystemServiceManager.startService(NotificationManagerService.class); // 通知管理 SystemNotificationChannels.removeDeprecated(context); SystemNotificationChannels.createAll(context); notification = INotificationManager.Stub.asInterface(ServiceManager.getService(Context.NOTIFICATION_SERVICE)); // "notification" mSystemServiceManager.startService(DeviceStorageMonitorService.class); // 磁盘空间状态检测服务 mSystemServiceManager.startService(LocationManagerService.Lifecycle.class); // 位置管理 try { countryDetector = new CountryDetectorService(context); // 检測用户国家 ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector); } catch (Throwable e) { reportWtf("starting Country Detector", e); } try { mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);// 时间检测。"com.android.server.timedetector.TimeDetectorService$Lifecycle" } catch (Throwable e) { reportWtf("starting StartTimeDetectorService service", e); } try { mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS); // 时区检测。"com.android.server.timezonedetector.TimeZoneDetectorService$Lifecycle" } catch (Throwable e) { reportWtf("starting StartTimeZoneDetectorService service", e); } if (!isWatch) { try { mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS); // 搜索服务。"com.android.server.search.SearchManagerService$Lifecycle" } catch (Throwable e) { reportWtf("starting Search Service", e); } } if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) { mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS); // 壁纸管理服务。"com.android.server.wallpaper.WallpaperManagerService$Lifecycle" } else { Slog.i(TAG, "Wallpaper service disabled by config"); } if (!isArc) { mSystemServiceManager.startService(AudioService.Lifecycle.class); // 音量、音效、声道及铃声等的管理 } else { // frameworks/base/core/res/res/values/config.xml // out/soong/.intermediates/frameworks/base/core/res/framework-res/android_common/gen/aapt2/R/com/android/internal/R.java String className = context.getResources().getString(R.string.config_deviceSpecificAudioService); // int config_deviceSpecificAudioService=0x01040207; 替换AudioService的设备特定实现的类名,如果使用默认值,则保持默认为空。 try { mSystemServiceManager.startService(className + "$Lifecycle"); } catch (Throwable e) { reportWtf("starting " + className, e); } } mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class); // 声音触发中间件服务 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) { mSystemServiceManager.startService(BroadcastRadioService.class); // 收音机 } mSystemServiceManager.startService(DockObserver.class); // dock(充电基座)观察器。管理座子的插入与拔出 if (isWatch) { mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS); // 温度监控。"com.google.android.clockwork.ThermalObserver" } try { // Listen for wired headset changes 聆听有线耳机的更改 inputManager.setWiredAccessoryCallbacks(new WiredAccessoryManager(context, inputManager)); // WiredAccessoryManager(有线辅助管理器) } catch (Throwable e) { reportWtf("starting WiredAccessoryManager", e); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) { // Start MIDI Manager service 启动MIDI管理器服务 "com.android.server.midi.MidiService$Lifecycle" mSystemServiceManager.startService(MIDI_SERVICE_CLASS); // MIDI设备服务。"com.android.server.midi.MidiService$Lifecycle" } // Start ADB Debugging Service 启动adb调试服务"com.android.server.adb.AdbService$Lifecycle" try { mSystemServiceManager.startService(ADB_SERVICE_CLASS); // adb(Android Debug Bridge),调试桥服务。"com.android.server.adb.AdbService$Lifecycle" } catch (Throwable e) { Slog.e(TAG, "Failure starting AdbService"); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY) || isEmulator) { // Manage USB host and device support 开启usb host和设备支持 "com.android.server.usb.UsbService$Lifecycle" mSystemServiceManager.startService(USB_SERVICE_CLASS); // USB设备管理,权限管控。"com.android.server.usb.UsbService$Lifecycle" } if (!isWatch) { try { // Serial port support 启动串口支持 serial = new SerialService(context); // 串口服务 ServiceManager.addService(Context.SERIAL_SERVICE, serial); } catch (Throwable e) { Slog.e(TAG, "Failure starting SerialService", e); } } try { hardwarePropertiesService = new HardwarePropertiesManagerService(context); // 设备硬件状态/属性 ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE, hardwarePropertiesService); } catch (Throwable e) { Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e); } mSystemServiceManager.startService(TwilightService.class); // 夜晚模式。根据位置信息来计算当前时间是白天还是夜晚 mSystemServiceManager.startService(ColorDisplayService.class); // 彩色模式显式 // TODO(aml-jobscheduler): Think about how to do it properly. mSystemServiceManager.startService(JOB_SCHEDULER_SERVICE_CLASS); // 任务调度服务。执行一定预定条件而触发的任务。"com.android.server.job.JobSchedulerService" mSystemServiceManager.startService(SoundTriggerService.class); // 语音识别服务。https://blog.csdn.net/lzqustc/article/details/117400134 mSystemServiceManager.startService(TrustManagerService.class); // 信任管理器服务 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) { mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS); // 备份管理。"com.android.server.backup.BackupManagerService$Lifecycle" } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS) || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) { mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS); // 桌面组件服务,允许用户的app以widget的形式放在桌面上。"com.android.server.appwidget.AppWidgetService" } // Grants default permissions and defines roles 授予默认权限并定义角色 mSystemServiceManager.startService(new RoleManagerService(mSystemContext, new LegacyRoleResolutionPolicy(mSystemContext))); // 默认应用管理。https://blog.csdn.net/weixin_42695485/article/details/109632385 // We need to always start this service, regardless of whether the FEATURE_VOICE_RECOGNIZERS feature is set, // because it needs to take care of initializing various settings. // It will internally modify its behavior based on that feature. // 我们需要始终启动此服务,无论是否设置了FEATURE_VOICE_RECOGNIZERS功能,因为它需要初始化各种设置。它将基于该特性在内部修改其行为。 mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS); // 语音交互管理器服务。"com.android.server.voiceinteraction.VoiceInteractionManagerService" if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) { mSystemServiceManager.startService(GestureLauncherService.class); // 手势启动器服务。https://blog.csdn.net/ouzhuangzhuang/article/details/82150180 } mSystemServiceManager.startService(SensorNotificationService.class); // 传感器通知服务 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CONTEXT_HUB)) { mSystemServiceManager.startService(ContextHubSystemService.class); // 上下文服务。 } try { ServiceManager.addService("diskstats", new DiskStatsService(context)); // 内部存储信息 } catch (Throwable e) { reportWtf("starting DiskStats Service", e); } try { ServiceManager.addService("runtime", new RuntimeService(context)); // 运行时服务。主要用于管理流程在运行时产生的数据 } catch (Throwable e) { reportWtf("starting RuntimeService", e); } // timezone.RulesManagerService will prevent a device starting up if the chain of trust required for safe time zone updates might be broken. // RuleManagerService cannot do this check when mOnlyCore == true, so we don't enable the service in this case. // This service requires that JobSchedulerService is already started when it starts. // 时区。如果安全时区更新所需的信任链可能中断,RulesManager服务将阻止设备启动。当mOnlyCore==true时,RuleManagerService无法执行此检查,因此在这种情况下我们不启用该服务。此服务要求JobSchedulerService在启动时已经启动。 final boolean startRulesManagerService = !mOnlyCore && context.getResources().getBoolean(R.bool.config_enableUpdateableTimeZoneRules); if (startRulesManagerService) { mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS); // 规则管理服务。"com.android.server.timezone.RulesManagerService$Lifecycle" } if (!isWatch && !disableNetworkTime) { try { networkTimeUpdater = new NetworkTimeUpdateService(context); // 网络时间更新。负责NTP时间获取 ServiceManager.addService("network_time_update_service", networkTimeUpdater); } catch (Throwable e) { reportWtf("starting NetworkTimeUpdate service", e); } } try { CertBlacklister blacklister = new CertBlacklister(context); } catch (Throwable e) { reportWtf("starting CertBlacklister", e); } if (EmergencyAffordanceManager.ENABLED) { // EmergencyMode service 启动应急模式服务 mSystemServiceManager.startService(EmergencyAffordanceService.class); // 紧急呼叫。https://source.android.google.cn/devices/tech/connect/emergency-affordance } mBlobStoreServiceStart = SystemServerInitThreadPool.submit(() -> { final TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(START_BLOB_STORE_SERVICE); mSystemServiceManager.startService(BLOB_STORE_MANAGER_SERVICE_CLASS); // 大型数据集。frameworks/base/services/java/com/android/server/SystemServer.java:262:"com.android.server.blob.BlobStoreManagerService"; traceLog.traceEnd(); }, START_BLOB_STORE_SERVICE); // Dreams (interactive idle-time views, a/k/a screen savers, and doze mode) 屏保服务 mSystemServiceManager.startService(DreamManagerService.class); // 屏保服务 ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE, new GraphicsStatsService(context)); //汇总屏幕卡顿数据的,通过adb shell dumpsys graphicsstats调用查看汇总结果 if (CoverageService.ENABLED) { ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService()); // 代码覆盖率服务 } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) { mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS); // 打印管理服务。"com.android.server.print.PrintManagerService" } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) { mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS); // 配对设备管理。"com.android.server.companion.CompanionDeviceManagerService" } mSystemServiceManager.startService(RestrictionsManagerService.class); // 限制管理器 mSystemServiceManager.startService(MediaSessionService.class); // 多媒体会话服务,在多个进程中共享多媒体播放状态 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) { mSystemServiceManager.startService(HdmiControlService.class); // hdmi控制服务 } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { mSystemServiceManager.startService(TvInputManagerService.class); //电视输入服务 } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TUNER)) { mSystemServiceManager.startService(TunerResourceManagerService.class); // 调谐器资源管理器。电视、多媒体等 } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) { mSystemServiceManager.startService(MediaResourceMonitorService.class); // 媒体资源监视器 } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) { mSystemServiceManager.startService(TvRemoteService.class); // 电视摇控服务 } try { mediaRouter = new MediaRouterService(context); // 媒体路由服务,用于给实现了Google Cast的设备提供远程播放、远程控制音乐和视频服务 ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter); } catch (Throwable e) { reportWtf("starting MediaRouterService", e); } final boolean hasFeatureFace = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE); final boolean hasFeatureIris = mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS); final boolean hasFeatureFingerprint = mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT); if (hasFeatureFace) { mSystemServiceManager.startService(FaceService.class); // 管理对人脸识别身份验证硬件的访问权限 } if (hasFeatureIris) { mSystemServiceManager.startService(IrisService.class); // 眼球虹膜 } if (hasFeatureFingerprint) { mSystemServiceManager.startService(FingerprintService.class); // 指纹服务 } // Start this service after all biometric services. 在完成所有生物识别服务后启动此服务。 mSystemServiceManager.startService(BiometricService.class); // 生物特征识别服务 mSystemServiceManager.startService(AuthService.class); // 身份认证服务 try { BackgroundDexOptService.schedule(context); // 后台优化 } catch (Throwable e) { reportWtf("starting StartBackgroundDexOptService", e); } if (!isWatch) { // We don't run this on watches as there are no plans to use the data logged on watch devices. // 我们不在手表上运行此功能,因为没有计划使用手表设备上记录的数据。 try { DynamicCodeLoggingService.schedule(context); // 动态化代码的日志记录服务。https://blog.csdn.net/dingpwen/article/details/106329152 } catch (Throwable e) { reportWtf("starting DynamicCodeLoggingService", e); } } if (!isWatch) { try { PruneInstantAppsJobService.schedule(context); // 优化快应用、即时应用、免安装应用 } catch (Throwable e) { reportWtf("StartPruneInstantAppsJobService", e); } } // LauncherAppsService uses ShortcutService. LAS会调用SS mSystemServiceManager.startService(ShortcutService.Lifecycle.class); // 快捷方式服务 mSystemServiceManager.startService(LauncherAppsService.class); // Launcher应用相关的服务 mSystemServiceManager.startService(CrossProfileAppsService.class); // 跨配置文件应用程序服务 mSystemServiceManager.startService(PeopleService.class); // google账号登录的人员基本信息服务。https://cloud.tencent.com/developer/article/1719204 } if (!isWatch) { mSystemServiceManager.startService(MediaProjectionManagerService.class); // 媒体投影服务,可用于录屏或者屏幕投射 } if (isWatch) { // Must be started before services that depend it, e.g. WearConnectivityService 必须在依赖它的服务之前启动,例如WearConnectionyService mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS); // 穿戴设备电源管理。"com.android.clockwork.power.WearPowerService" mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS); // 穿戴设备连接。"com.android.clockwork.connectivity.WearConnectivityService" mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS); // 穿戴设备显示。"com.google.android.clockwork.display.WearDisplayService" mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS); // 穿戴设备时间。"com.google.android.clockwork.time.WearTimeService" if (enableLeftyService) { mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS); // 穿戴设备左撇子模式。"com.google.android.clockwork.lefty.WearLeftyService" } mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS); // 穿戴设备全球化。"com.android.clockwork.globalactions.GlobalActionsService" } if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED)) { mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS); // 静音管理。"com.android.server.slice.SliceManagerService$Lifecycle" } if (!disableCameraService) { mSystemServiceManager.startService(CameraServiceProxy.class); // 摄像头。 } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) { mSystemServiceManager.startService(IOT_SERVICE_CLASS); // 物联网。"com.android.things.server.IoTSystemService" } // Statsd helper mSystemServiceManager.startServiceFromJar(STATS_COMPANION_LIFECYCLE_CLASS, STATS_COMPANION_APEX_PATH); // 启动信息收集服务。"com.android.server.stats.StatsCompanion$Lifecycle","/apex/com.android.os.statsd/javalib/service-statsd.jar" // Statsd pulled atoms mSystemServiceManager.startService(STATS_PULL_ATOM_SERVICE_CLASS); // 启动信息统计上报服务。"com.android.server.stats.pull.StatsPullAtomService" // Incidentd and dumpstated helper 意外和转储声明的帮助程序 mSystemServiceManager.startService(IncidentCompanionService.class); // 意外信息收集服务 if (safeMode) { mActivityManagerService.enterSafeMode(); } // MMS service broker 彩信服务 mmsService = mSystemServiceManager.startService(MmsServiceBroker.class); // 彩信服务 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) { mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS); // 自动填充服务,比如自动填充密码。"com.android.server.autofill.AutofillManagerService" } // NOTE: ClipboardService depends on ContentCapture and Autofill 剪贴板服务依赖于内容捕获和自动填充 mSystemServiceManager.startService(ClipboardService.class); // 剪贴板服务 mSystemServiceManager.startService(AppBindingService.Lifecycle.class); // 应用程序绑定服务 final Class<?> serverClazz; try { serverClazz = Class.forName(externalServer); // 上面定义的,扩展的/外部的系统。lineage-sdk/lineage/lib/main/java/org/lineageos/platform/internal/LineageSystemServer.java final Constructor<?> constructor = serverClazz.getDeclaredConstructor(Context.class); constructor.setAccessible(true); final Object baseObject = constructor.newInstance(mSystemContext); final Method method = baseObject.getClass().getDeclaredMethod("run"); method.setAccessible(true); method.invoke(baseObject); } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException e) { Slog.wtf(TAG, "Unable to start " + externalServer); Slog.wtf(TAG, e); } // It is now time to start up the app processes... // 现在是启动应用程序进程的时候了。。。 try { vibrator.systemReady(); } catch (Throwable e) { reportWtf("making Vibrator Service ready", e); } if (lockSettings != null) { try { lockSettings.systemReady(); } catch (Throwable e) { reportWtf("making Lock Settings Service ready", e); } } // Needed by DevicePolicyManager for initialization. DevicePolicyManager需要进行初始化 mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY); try { wm.systemReady(); } catch (Throwable e) { reportWtf("making Window Manager Service ready", e); } // Emit any pending system_server WTFs.发出任何挂起的system_server WTF synchronized (SystemService.class) { if (sPendingWtfs != null) { mActivityManagerService.schedulePendingSystemServerWtfs(sPendingWtfs); sPendingWtfs = null; } } if (safeMode) { mActivityManagerService.showSafeModeOverlay(); } // Update the configuration for this context by hand, because we're going to start using it // before the config change done in wm.systemReady() will propagate to it. // 手动更新此上下文的配置,因为我们将在wm中完成配置更改之前开始使用它。systemReady()将传播到它。 final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY); DisplayMetrics metrics = new DisplayMetrics(); context.getDisplay().getMetrics(metrics); context.getResources().updateConfiguration(config, metrics); // The system context's theme may be configuration-dependent. 系统上下文的主题可能取决于配置。 final Theme systemTheme = context.getTheme(); if (systemTheme.getChangingConfigurations() != 0) { systemTheme.rebase(); } try { // TODO: use boot phase mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService()); } catch (Throwable e) { reportWtf("making Power Manager Service ready", e); } // Permission policy service 权限策略服务 mSystemServiceManager.startService(PermissionPolicyService.class); // 权限策略服务 mPackageManagerService.systemReady(); try { // TODO: use boot phase and communicate these flags some other way mDisplayManagerService.systemReady(safeMode, mOnlyCore); } catch (Throwable e) { reportWtf("making Display Manager Service ready", e); } mSystemServiceManager.setSafeMode(safeMode); // Start device specific services 启动特定于设备的服务 // 继承“com.android.server.SystemService”的设备特定服务的类名,这些类按照数组的顺序进行实例化。frameworks/base/core/res/res/values/config.xml final String[] classes = mSystemContext.getResources().getStringArray(R.array.config_deviceSpecificSystemServices); for (final String className : classes) { try { mSystemServiceManager.startService(className); // 如果有的话,启动 } catch (Throwable e) { reportWtf("starting " + className, e); } } mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY); ConcurrentUtils.waitForFutureNoInterrupt(mBlobStoreServiceStart, START_BLOB_STORE_SERVICE); // These are needed to propagate to the runnable below. 这些需要传播到下面的可运行状态。 final NetworkManagementService networkManagementF = networkManagement; final NetworkStatsService networkStatsF = networkStats; final NetworkPolicyManagerService networkPolicyF = networkPolicy; final ConnectivityService connectivityF = connectivity; final CountryDetectorService countryDetectorF = countryDetector; final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater; final InputManagerService inputManagerF = inputManager; final TelephonyRegistry telephonyRegistryF = telephonyRegistry; final MediaRouterService mediaRouterF = mediaRouter; final MmsServiceBroker mmsServiceF = mmsService; final IpSecService ipSecServiceF = ipSecService; final WindowManagerService windowManagerF = wm; // We now tell the activity manager it is okay to run third party code. // It will call back into us once it has gotten to the state where third party code can really run // (but before it has actually started launching the initial applications), // for us to complete our initialization. // 现在,我们告诉活动管理器可以运行第三方代码。一旦它达到第三方代码可以真正运行的状态(但在它实际启动初始应用程序之前),它将回调给我们,以便我们完成初始化。 mActivityManagerService.systemReady(() -> { Slog.i(TAG, "Making services ready"); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY); try { mActivityManagerService.startObservingNativeCrashes(); // 启动1个native的崩溃信息监听器。 } catch (Throwable e) { reportWtf("observing native crashes", e); } // No dependency on Webview preparation in system server. But this should be completed before allowing 3rd party // 不依赖于system server中的Webview准备。但这应该在允许第三方之前完成 final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation"; Future<?> webviewPrep = null; if (!mOnlyCore && mWebViewUpdateService != null) { webviewPrep = SystemServerInitThreadPool.submit(() -> { Slog.i(TAG, WEBVIEW_PREPARATION); TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(WEBVIEW_PREPARATION); ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload"); mZygotePreload = null; mWebViewUpdateService.prepareWebViewInSystemServer(); traceLog.traceEnd(); }, WEBVIEW_PREPARATION); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) { mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS); // 汽车模式助手。frameworks/base/services/java/com/android/server/SystemServer.java:254:"com.android.internal.car.CarServiceHelperService"; } try { startSystemUi(context, windowManagerF); // 2557行。用户界面。【--- 7 ---】 } catch (Throwable e) { reportWtf("starting System UI", e); } // Enable airplane mode in safe mode. setAirplaneMode() cannot be called earlier as it sends broadcasts to other services. // TODO: This may actually be too late if radio firmware already started leaking RF before the respective services start. // However, fixing this requires changes to radio firmware and interfaces. // 在安全模式下启用飞行模式。setAirplaneMode()无法提前调用,因为它向其他服务发送广播。但是,修复此问题需要更改无线电固件和接口。 if (safeMode) { try { connectivityF.setAirplaneMode(true); } catch (Throwable e) { reportWtf("enabling Airplane Mode during Safe Mode bootup", e); } } try { if (networkManagementF != null) { networkManagementF.systemReady(); } } catch (Throwable e) { reportWtf("making Network Managment Service ready", e); } CountDownLatch networkPolicyInitReadySignal = null; if (networkPolicyF != null) { networkPolicyInitReadySignal = networkPolicyF.networkScoreAndNetworkManagementServiceReady(); } try { if (ipSecServiceF != null) { ipSecServiceF.systemReady(); } } catch (Throwable e) { reportWtf("making IpSec Service ready", e); } try { if (networkStatsF != null) { networkStatsF.systemReady(); } } catch (Throwable e) { reportWtf("making Network Stats Service ready", e); } try { if (connectivityF != null) { connectivityF.systemReady(); } } catch (Throwable e) { reportWtf("making Connectivity Service ready", e); } try { if (networkPolicyF != null) { networkPolicyF.systemReady(networkPolicyInitReadySignal); } } catch (Throwable e) { reportWtf("making Network Policy Service ready", e); } // Wait for all packages to be prepared. 等待准备好所有包 mPackageManagerService.waitForAppDataPrepared(); // It is now okay to let the various system services start their third party code... // 现在可以让各种系统服务启动其第三方代码。。。 // confirm webview completion before starting 3rd party. 启动第三方之前确认webview完成 if (webviewPrep != null) { ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION); } mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); try { // Note : the network stack is creating on-demand objects that need to send broadcasts, // which means it currently depends on being started after ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady // are set to true. Be careful if moving this to a different place in the startup sequence. // 注意:网络堆栈正在创建需要发送广播的按需对象,这意味着它目前取决于在ActivityManagerService之后启动。MSSystemReady和ActivityManager服务。MProcessReady设置为true。如果将其移动到启动顺序中的其他位置,请小心。 NetworkStackClient.getInstance().start(); // 用于与网络堆栈通信的服务,网络堆栈在单独的模块中运行。frameworks/base/services/net/java/android/net/NetworkStackClient.java } catch (Throwable e) { reportWtf("starting Network Stack", e); } try { // TODO: hide implementation details, b/146312721. ConnectivityModuleConnector.getInstance().startModuleService( TETHERING_CONNECTOR_CLASS, // "android.net.ITetheringConnector"; 网络共享。frameworks/base/packages/Tethering/src/com/android/networkstack/tethering/TetheringService.java PERMISSION_MAINLINE_NETWORK_STACK, // "android.permission.MAINLINE_NETWORK_STACK" service -> { // ServiceManager.addService(Context.TETHERING_SERVICE, service, false /* allowIsolated */, DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL); } ); } catch (Throwable e) { reportWtf("starting Tethering", e); } try { if (countryDetectorF != null) { countryDetectorF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying CountryDetectorService running", e); } try { if (networkTimeUpdaterF != null) { networkTimeUpdaterF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying NetworkTimeService running", e); } try { // TODO(BT) Pass parameter to input manager if (inputManagerF != null) { inputManagerF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying InputManagerService running", e); } try { if (telephonyRegistryF != null) { telephonyRegistryF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying TelephonyRegistry running", e); } try { if (mediaRouterF != null) { mediaRouterF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying MediaRouterService running", e); } try { if (mmsServiceF != null) { mmsServiceF.systemRunning(); } } catch (Throwable e) { reportWtf("Notifying MmsService running", e); } try { // TODO: Switch from checkService to getService once it's always in the build and should reliably be there. final IIncidentManager incident = IIncidentManager.Stub.asInterface(ServiceManager.getService(Context.INCIDENT_SERVICE)); if (incident != null) { incident.systemRunning(); // } } catch (Throwable e) { reportWtf("Notifying incident daemon running", e); } if (mIncrementalServiceHandle != 0) { setIncrementalServiceSystemReady(mIncrementalServiceHandle); } }, t); // end mActivityManagerService.systemReady() } // end startOtherServices |
6.1 startContentCaptureService
启动内容监听服务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// 2510行 private void startContentCaptureService(@NonNull Context context, @NonNull TimingsTraceAndSlog t) { // First check if it was explicitly enabled by DeviceConfig boolean explicitlyEnabled = false; String settings = DeviceConfig.getProperty(DeviceConfig.NAMESPACE_CONTENT_CAPTURE, ContentCaptureManager.DEVICE_CONFIG_PROPERTY_SERVICE_EXPLICITLY_ENABLED); if (settings != null && !settings.equalsIgnoreCase("default")) { explicitlyEnabled = Boolean.parseBoolean(settings); if (explicitlyEnabled) { Slog.d(TAG, "ContentCaptureService explicitly enabled by DeviceConfig"); } else { Slog.d(TAG, "ContentCaptureService explicitly disabled by DeviceConfig"); return; } } // Then check if OEM overlaid the resource that defines the service. if (!explicitlyEnabled) { if (!deviceHasConfigString(context, R.string.config_defaultContentCaptureService)) { Slog.d(TAG, "ContentCaptureService disabled because resource is not overlaid"); return; } } t.traceBegin("StartContentCaptureService"); mSystemServiceManager.startService(CONTENT_CAPTURE_MANAGER_SERVICE_CLASS); // 内容监听服务。"com.android.server.contentcapture.ContentCaptureManagerService" ContentCaptureManagerInternal ccmi = LocalServices.getService(ContentCaptureManagerInternal.class); // 为应用程序提供与内容捕获子系统集成的其他方法。 if (ccmi != null && mActivityManagerService != null) { mActivityManagerService.setContentCaptureManager(ccmi); } t.traceEnd(); } // end startContentCaptureService |
6.2 startAttentionService
注意力服务?
1 2 3 4 5 6 7 8 9 10 11 |
// 2545行 private void startAttentionService(@NonNull Context context, @NonNull TimingsTraceAndSlog t) { if (!AttentionManagerService.isServiceConfigured(context)) { Slog.d(TAG, "AttentionService is not configured on this device"); return; } t.traceBegin("StartAttentionManagerService"); mSystemServiceManager.startService(AttentionManagerService.class); // 注意力服务 t.traceEnd(); } |
6.3 startSystemCaptionsManagerService
系统标题管理器服务
1 2 3 4 5 6 7 8 9 10 11 |
// 2498行 private void startSystemCaptionsManagerService(@NonNull Context context, @NonNull TimingsTraceAndSlog t) { if (!deviceHasConfigString(context, R.string.config_defaultSystemCaptionsManagerService)) { Slog.d(TAG, "SystemCaptionsManagerService disabled because resource is not overlaid"); return; } t.traceBegin("StartSystemCaptionsManagerService"); mSystemServiceManager.startService(SYSTEM_CAPTIONS_MANAGER_SERVICE_CLASS); // 系统标题管理器服务。"com.android.server.systemcaptions.SystemCaptionsManagerService" t.traceEnd(); } |
7. startSystemUi
通过Intent启动SystemUIService。下一篇看一下服务内部的流程。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// 2557行 private static void startSystemUi(Context context, WindowManagerService windowManager) { PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class); // PackageManager本地(local)系统服务接口。暴露私有服务,用于系统组件的使用 // frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java:24172:private class PackageManagerInternalImpl extends PackageManagerInternal Intent intent = new Intent(); // frameworks/base/core/res/res/values/config.xml:2696:com.android.systemui/com.android.systemui.SystemUIService // frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIService.java intent.setComponent(pm.getSystemUiServiceComponent()); intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); //Slog.d(TAG, "Starting service: " + intent); context.startServiceAsUser(intent, UserHandle.SYSTEM); windowManager.onSystemUiStarted(); } |
- end
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/4098.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设