本篇文章主要介紹 Android
開發中 SystemServer進程啓動 部分知識點,經過閱讀本篇文章,您將收穫如下內容:java
1、SystemServer 啓動的服務有哪些
2、SystemServer啓動整體流程概述
3、SystemServer 如何啓動,是誰啓動的?
4、 SystemServer 啓動入門 main 方法
5、SystemServer Run 方法初始與啓動
6、SystemServer 的引導服務有哪些
7、SystemServer 的核心服務有哪些
8、SystemServer 的其餘服務有哪些
SystemServer
主要啓動 ActivityManagerService
、PackageManagerService
、WindowManagerService
、LightsService
、LightsService
、BatteryService
、TelephonyRegistry
、RecoverySystemService
等等,主要分三大類,後文會詳細列舉。react
SystemServer 啓動的服務 做用以下:android
SystemServer 代碼路徑:程序員
\alps\frameworks\base\services\java\com\android\server\SystemServer.java
bootstrap
SystemServer
是經過Zygote
啓動的,在ZygoteInit.java
類的(frameworks\base\core\java\com\android\internal\os\ZygoteInit.java)
main
方法中經過forkSystemServer
啓動。緩存
public static void main(String argv[]) { .... //設置變量區分是否啓動SystemServer boolean startSystemServer = false; String socketName = "zygote"; String abiList = null; boolean enableLazyPreload = false; for (int i = 1; i < argv.length; i++) { if ("start-system-server".equals(argv[i])) { // 須要啓動時候,將標誌位設置爲true startSystemServer = true; } else if ("--enable-lazy-preload".equals(argv[i])) { enableLazyPreload = true; } ... ... if (startSystemServer) { // 經過 Zygote fork 出 SystemServer Runnable r = forkSystemServer(abiList, socketName, zygoteServer); // {@code r == null} in the parent (zygote) process, and {@code r != null} in the // child (system_server) process. if (r != null) { r.run(); return; } }
main
入口 經過 new SystemServer().run();
開啓SystemServer
啓動。微信
main
入口代碼以下:app
/** * The main entry point from zygote. */ public static void main(String[] args) { new SystemServer().run(); }
經過Main
入口,調用SystemServer
構造方法。less
public SystemServer() { // 檢查工程模式. mFactoryTestMode = FactoryTest.getMode(); // 判斷是不是重啓 mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed")); mRuntimeStartElapsedTime = SystemClock.elapsedRealtime(); mRuntimeStartUptime = SystemClock.uptimeMillis(); } private void run() { ... ... }
SystemServer Run 方法 代碼socket
private void run() { try { traceBeginAndSlog("InitBeforeStartServices"); //初始化時間 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } //設置默認時區 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"); } ... ... // 開始進入Android SystemServer Slog.i(TAG, "Entered the Android system server!"); int uptimeMillis = (int) SystemClock.elapsedRealtime(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis); if (!mRuntimeRestart) { MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis); } ... ... //若是支持指紋,需初始化指紋ro.build.fingerprint Build.ensureFingerprintProperty(); ... ... // 初始化 native services. System.loadLibrary("android_servers"); // 檢查最近一次關機是否失敗 performPendingShutdown(); // 初始化 the system context. createSystemContext(); // 建立 system service manager. mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // 初始化SystemServer 線程池 SystemServerInitThreadPool.get(); } finally { traceEnd(); // InitBeforeStartServices } ... ... // 開始啓動 services. try { traceBeginAndSlog("StartServices"); // 1. 啓動引導服務 詳見分析六 startBootstrapServices(); // 2. 啓動核心服務 詳見分析七 startCoreServices(); // 3.啓動其餘服務 詳見分析八 startOtherServices(); SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { traceEnd(); } StrictMode.initVmDefaults(null); }
SystemServer
啓動的經常使用引導服務有 installed 、DeviceIdentifiersPolicyService、 ActivityManagerService.、PowerManagerService 、 RecoverySystemService 、 LightsService 、 PackageManagerService、UserManagerService、OverlayManagerService
等。
startBootstrapServices代碼部分以下:
/** * 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() { Slog.i(TAG, "Reading configuration..."); final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig"; traceBeginAndSlog(TAG_SYSTEM_CONFIG); SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG); traceEnd(); // 啓動 installed traceBeginAndSlog("StartInstaller"); Installer installer = mSystemServiceManager.startService(Installer.class); traceEnd(); //啓動 設備標識符 服務 traceBeginAndSlog("DeviceIdentifiersPolicyService"); mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class); traceEnd(); // 啓動 AMS. traceBeginAndSlog("StartActivityManager"); mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); traceEnd(); //啓動 PMS traceBeginAndSlog("StartPowerManager"); mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); traceEnd(); //初始化電源管理功能 traceBeginAndSlog("InitPowerManagement"); mActivityManagerService.initPowerManagement(); traceEnd(); // 啓動 RecoverySystemService traceBeginAndSlog("StartRecoverySystemService"); mSystemServiceManager.startService(RecoverySystemService.class); traceEnd(); // 爲啓動事件添加記錄 RescueParty.noteBoot(mSystemContext); // 啓動 LightsService 管理LEDs 和背光顯示 traceBeginAndSlog("StartLightsService"); mSystemServiceManager.startService(LightsService.class); traceEnd(); traceBeginAndSlog("StartSidekickService"); // Package manager isn't started yet; need to use SysProp not hardware feature if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) { mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS); } traceEnd(); // Display manager is needed to provide display metrics before package manager // starts up. traceBeginAndSlog("StartDisplayManager"); mDisplayManagerService = mSystemServiceManager.startService(LightsService.class); traceEnd(); // We need the default display before we can initialize the package manager. traceBeginAndSlog("WaitForDisplay"); mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); traceEnd(); // Only run "core" apps if we're encrypting the device. String cryptState = SystemProperties.get("vold.decrypt"); 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; } // 啓動 PackageManagerService if (!mRuntimeRestart) { MetricsLogger.histogram(null, "boot_package_manager_init_start", (int) SystemClock.elapsedRealtime()); } traceBeginAndSlog("StartPackageManagerService"); mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); traceEnd(); if (!mRuntimeRestart && !isFirstBootOrUpgrade()) { MetricsLogger.histogram(null, "boot_package_manager_init_ready", (int) 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). if (!mOnlyCore) { boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false); if (!disableOtaDexopt) { traceBeginAndSlog("StartOtaDexOptService"); try { OtaDexoptService.main(mSystemContext, mPackageManagerService); } catch (Throwable e) { reportWtf("starting OtaDexOptService", e); } finally { traceEnd(); } } } //啓動多用戶 UserManagerService traceBeginAndSlog("StartUserManagerService"); mSystemServiceManager.startService(UserManagerService.LifeCycle.class); traceEnd(); // 初始化屬性緩存 traceBeginAndSlog("InitAttributerCache"); AttributeCache.init(mSystemContext); traceEnd(); // Set up the Application instance for the system process and get started. traceBeginAndSlog("SetSystemProcess"); mActivityManagerService.setSystemProcess(); traceEnd(); // DisplayManagerService needs to setup android.display scheduling related policies // since setSystemProcess() would have overridden policies due to setProcessGroup mDisplayManagerService.setupSchedulerPolicies(); /// M: CTA requirement - permission control @{ /* * M: MOTA for CTA permissions handling * This function is used for granting CTA permissions after OTA upgrade. * This should be placed after AMS is added to ServiceManager and before * starting other services since granting permissions needs AMS instance * to do permission checking. */ mPackageManagerService.onAmsAddedtoServiceMgr(); /// @} // 啓動 OverlayManagerService traceBeginAndSlog("StartOverlayManagerService"); mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer)); traceEnd(); // 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. mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> { TimingsTraceLog traceLog = new TimingsTraceLog( SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER); traceLog.traceBegin(START_SENSOR_SERVICE); startSensorService(); traceLog.traceEnd(); }, START_SENSOR_SERVICE); }
SystemServer 核心服務 有 BatteryService 、UsageStatsService、WebViewUpdateService、BinderCallsStatsService
4種核心服務。
startCoreServices 代碼部分以下:
/** * Starts some essential services that are not tangled up in the bootstrap process. */ private void startCoreServices() { // 啓動 BatteryService 管理電池服務(電壓、電量、溫度) traceBeginAndSlog("StartBatteryService"); // Tracks the battery level. Requires LightService. mSystemServiceManager.startService(BatteryService.class); traceEnd(); // 啓動 UsageStatsService 收集應用持久化數據的服務 traceBeginAndSlog("StartUsageService"); mSystemServiceManager.startService(UsageStatsService.class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); traceEnd(); // 啓動 WebViewUpdateService 監視 WebView 是否更新 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { traceBeginAndSlog("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); traceEnd(); } //啓動 CPU Binder 調度服務 traceBeginAndSlog("StartBinderCallsStatsService"); BinderCallsStatsService.start(); traceEnd(); }
startOtherServices 啓動的服務主要有: `KeyChainSystemService、TelecomLoaderService、AccountManagerService、ContentService、DropBoxManagerService、VibratorService、AlarmManagerService、Watchdog、
InputManagerService、WindowManagerService、IpConnectivityMetrics、NetworkWatchlistService、PinnerService`等服務。
startOtherServices
代碼部分以下:
/** * Starts a miscellaneous grab bag of stuff that has yet to be refactored * and organized. */ private void startOtherServices() { ... ... traceBeginAndSlog("StartKeyAttestationApplicationIdProviderService"); ServiceManager.addService("sec_key_att_app_id_provider", new KeyAttestationApplicationIdProviderService(context)); traceEnd(); // 啓動 KeyChainSystemService traceBeginAndSlog("StartKeyChainSystemService"); mSystemServiceManager.startService(KeyChainSystemService.class); traceEnd(); traceBeginAndSlog("StartSchedulingPolicyService"); ServiceManager.addService("scheduling_policy", new SchedulingPolicyService()); traceEnd(); // 啓動 TelecomLoaderService traceBeginAndSlog("StartTelecomLoaderService"); mSystemServiceManager.startService(TelecomLoaderService.class); traceEnd(); traceBeginAndSlog("StartTelephonyRegistry"); telephonyRegistry = new TelephonyRegistry(context); ServiceManager.addService("telephony.registry", telephonyRegistry); traceEnd(); traceBeginAndSlog("StartEntropyMixer"); mEntropyMixer = new EntropyMixer(context); traceEnd(); mContentResolver = context.getContentResolver(); // 啓動 用戶管理服務 ,必如今StartContentService 以前 traceBeginAndSlog("StartAccountManagerService"); mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS); traceEnd(); // 啓動 ContentService traceBeginAndSlog("StartContentService"); mSystemServiceManager.startService(CONTENT_SERVICE_CLASS); traceEnd(); // 安裝系統Provider 例如 SettingProvider CantacttProvider traceBeginAndSlog("InstallSystemProviders"); mActivityManagerService.installSystemProviders(); // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags SQLiteCompatibilityWalFlags.reset(); traceEnd(); // 啓動 DropBoxManagerService // 因爲 依賴SettingsProvider,必須在InstallSystemProviders以後啓動 traceBeginAndSlog("StartDropBoxManager"); mSystemServiceManager.startService(DropBoxManagerService.class); traceEnd(); //啓動 VibratorService 震動服務 traceBeginAndSlog("StartVibratorService"); vibrator = new VibratorService(context); ServiceManager.addService("vibrator", vibrator); traceEnd(); if (!isWatch) { traceBeginAndSlog("StartConsumerIrService"); consumerIr = new ConsumerIrService(context); ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); traceEnd(); } // 啓動 AlarmManagerService traceBeginAndSlog("StartAlarmManagerService"); if(!sMtkSystemServerIns.startMtkAlarmManagerService()){ mSystemServiceManager.startService(AlarmManagerService.class); } traceEnd(); // 初始化 看門狗 traceBeginAndSlog("InitWatchdog"); final Watchdog watchdog = Watchdog.getInstance(); watchdog.init(context, mActivityManagerService); traceEnd(); //啓動 InputManagerService traceBeginAndSlog("StartInputManagerService"); inputManager = new InputManagerService(context); traceEnd(); //啓動 WindowManagerService traceBeginAndSlog("StartWindowManagerService"); // WMS needs sensor service ready ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE); mSensorServiceStart = null; wm = WindowManagerService.main(context, inputManager, mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, !mFirstBoot, mOnlyCore, new PhoneWindowManager()); ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); ServiceManager.addService(Context.INPUT_SERVICE, inputManager, /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); traceEnd(); traceBeginAndSlog("SetWindowManagerService"); mActivityManagerService.setWindowManager(wm); traceEnd(); traceBeginAndSlog("WindowManagerServiceOnInitReady"); wm.onInitReady(); traceEnd(); // 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. SystemServerInitThreadPool.get().submit(() -> { TimingsTraceLog traceLog = new TimingsTraceLog( SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER); traceLog.traceBegin(START_HIDL_SERVICES); startHidlServices(); traceLog.traceEnd(); }, START_HIDL_SERVICES); if (!isWatch) { traceBeginAndSlog("StartVrManagerService"); mSystemServiceManager.startService(VrManagerService.class); traceEnd(); } traceBeginAndSlog("StartInputManager"); inputManager.setWindowManagerCallbacks(wm.getInputMonitor()); inputManager.start(); traceEnd(); // TODO: Use service dependencies instead. traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady"); mDisplayManagerService.windowManagerAndInputReady(); traceEnd(); // Skip Bluetooth if we have an emulator kernel // TODO: Use a more reliable check to see if this product should // support Bluetooth - see bug 988521 if (isEmulator) { Slog.i(TAG, "No Bluetooth Service (emulator)"); } else 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 { traceBeginAndSlog("StartBluetoothService"); mSystemServiceManager.startService(BluetoothService.class); traceEnd(); } // 啓動 IpConnectivityMetrics traceBeginAndSlog("IpConnectivityMetrics"); mSystemServiceManager.startService(IpConnectivityMetrics.class); traceEnd(); // 啓動 NetworkWatchlistService traceBeginAndSlog("NetworkWatchlistService"); mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class); traceEnd(); // 啓動 PinnerService traceBeginAndSlog("PinnerService"); mSystemServiceManager.startService(PinnerService.class); traceEnd(); } catch (RuntimeException e) {
至此,本篇已結束,若有不對的地方,歡迎您的建議與指正。同時期待您的關注,感謝您的閱讀,謝謝!