Android10 啟動之SystemServer源碼分析
正文
上一篇文章: # Android 10 啟動分析之Zygote篇 (三)
緊接著上一篇文章的內容,我們從這篇文章開始來分析一下 SystemServer。
system_server 進程承載著整個framework的核心服務,例如創(chuàng)建 ActivityManagerService、PowerManagerService、DisplayManagerService、PackageManagerService、WindowManagerService、LauncherAppsService等80多個核心系統(tǒng)服務。這些服務以不同的線程方式存在于system_server這個進程中。
SystemServer的源碼路徑為 /frameworks/base/services/java/com/android/server/SystemServer.java
,我們從這個類的main方法開始看起:
public static void main(String[] args) { new SystemServer().run(); }
main方法里創(chuàng)建了一個SystemServer實例,并調用了run方法。SystemServer的構造方法里只是一些簡單的變量初始化,我們直接從run方法繼續(xù)閱讀。
private void run() { try { ... //準備主線程lopper android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // 加載libandroid_servers.so庫 System.loadLibrary("android_servers"); //檢測上次關機過程是否失敗,這個調用可能不會返回 performPendingShutdown(); //初始化系統(tǒng)上下文 createSystemContext(); //創(chuàng)建系統(tǒng)服務管理者--SystemServiceManager mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); //將mSystemServiceManager添加到本地服務中,至于什么是LocalServices,它有什么作用, //以后再單獨開一篇文章來講解 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); //為可以并行化的init任務準備線程池 SystemServerInitThreadPool.get(); } finally { traceEnd(); // InitBeforeStartServices } // 在這里開始啟動一系列服務了 try { traceBeginAndSlog("StartServices"); // 啟動引導服務 startBootstrapServices(); // 啟動核心服務 startCoreServices(); // 啟動其他服務 startOtherServices(); //停止init線程池 SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { traceEnd(); } ... // 死循環(huán)執(zhí)行 Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
我們來關注以下幾個重點方法:
createSystemContext
private void createSystemContext() { //創(chuàng)建system_server進程的上下文信息 ActivityThread activityThread = ActivityThread.systemMain(); mSystemContext = activityThread.getSystemContext(); //設置主題 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); //獲取systemui上下文信息,并設置主題 final Context systemUiContext = activityThread.getSystemUiContext(); systemUiContext.setTheme(DEFAULT_SYSTEM_THEME); }
在調用ActivityThread.systemMain方法時,這個過程會創(chuàng)建對象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application。
為什么會要創(chuàng)建Application對象?就目前的源碼來看,Application對象在systemserver進程并無實際作用,筆者只能猜測這是為將來的擴展做準備或者android版本迭代中的歷史遺留代碼。
startBootstrapServices
在這個方法中會啟動系統(tǒng)的關鍵服務,這些服務是系統(tǒng)運行的基石。因為它們之間具有復雜的依賴關系,所以谷歌把它們放在一起初始化。
private void startBootstrapServices() { // 盡早啟動看門狗,這樣我們在早期啟動陷入死鎖時就可以使system server崩潰重啟。 final Watchdog watchdog = Watchdog.getInstance(); watchdog.start(); //啟動Installer Service,這個Service 通過binder與installd進程通訊,負責apk安裝相關的工作 Installer installer = mSystemServiceManager.startService(Installer.class); //設備標識符策略服務 mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class); // 管理uri授權 mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class); //啟動ActivityTaskManagerService和ActivityManagerService ActivityTaskManagerService atm = mSystemServiceManager.startService( ActivityTaskManagerService.Lifecycle.class).getService(); mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); //電源管理器需要盡早啟動,因為其他服務需要它。 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); //啟動熱緩解服務,目的是在手機開始過熱時進行有效的熱緩解 mSystemServiceManager.startService(ThermalManagerService.class); // Now that the power manager has been started, let the activity manager // initialize power management features. mActivityManagerService.initPowerManagement(); //啟動系統(tǒng)恢復服務,負責協(xié)調設備上與恢復有關的功能。 mSystemServiceManager.startService(RecoverySystemService.class); //到這里為止,系統(tǒng)啟動的必須服務已經(jīng)加載完畢 RescueParty.noteBoot(mSystemContext); //管理LED和屏幕背光,我們需要它來顯示 mSystemServiceManager.startService(LightsService.class); //管理顯示設備 //在package manager 啟動之前,需要啟動display manager 提供display metrics mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class); //只有DisplayManagerService會對PHASE_WAIT_FOR_DEFAULT_DISPLAY做處理 //目的是在初始化包管理器之前,首先需要獲取一個默認的顯示設備 mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); // 啟動 package manager. if (!mRuntimeRestart) { MetricsLogger.histogram(null, "boot_package_manager_init_start", (int) SystemClock.elapsedRealtime()); } try { Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain"); mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain"); } mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); //啟動UserManager Service mSystemServiceManager.startService(UserManagerService.LifeCycle.class); //為系統(tǒng)進程設置應用程序實例并啟動 mActivityManagerService.setSystemProcess(); //使用ActivityManager實例完成看門狗設置并監(jiān)聽是否重啟 watchdog.init(mSystemContext, mActivityManagerService); // DisplayManagerService needs to setup android.display scheduling related policies // since setSystemProcess() would have overridden policies due to setProcessGroup mDisplayManagerService.setupSchedulerPolicies(); //負責動態(tài)資源overlay mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer)); mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext)); if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) { // DisplayManager needs the overlay immediately. mActivityManagerService.updateSystemUiContext(); LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged(); } //傳感器服務需要訪問包管理器服務、app ops服務和權限服務, //因此我們在它們之后啟動它。 //在單獨的線程中啟動傳感器服務。在使用它之前應該檢查完成情況。 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); }
總結一下,引導服務有以下15個:
服務名稱 | 描述 |
---|---|
Installer | 負責apk安裝相關的工作 |
DeviceIdentifiersPolicyService | 設備標識符策略服務 |
UriGrantsManagerService | Uri授權管理 |
ActivityTaskManagerService | 用于管理Activity及其容器(task, stacks, displays,... )的系統(tǒng)服務 |
ActivityManagerService | 管理Activity的啟動,調度等工作 |
PowerManagerService | 負責協(xié)調設備上的電源管理功能 |
ThermalManagerService | 熱緩解服務 |
RecoverySystemService | 負責協(xié)調設備上與恢復有關的功能 |
LightsService | 管理LED和屏幕背光 |
DisplayManagerService | 管理顯示設備 |
PackageManagerService | 主要負責APK、jar包的管理 |
UserManagerService | 管理用戶的系統(tǒng)服務 |
OverlayManagerService | 負責動態(tài)資源overlay工作,具體請搜索android RRO技術 |
SensorPrivacyService | 和傳感器有關,具體作用不明 |
SensorPrivacySere | 傳感器服務 |
startCoreServices
private void startCoreServices() { // 追蹤電池充電狀態(tài)和電量。需要LightService mSystemServiceManager.startService(BatteryService.class); //跟蹤應用程序使用狀態(tài) mSystemServiceManager.startService(UsageStatsService.class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); // 跟蹤可更新的WebView是否處于就緒狀態(tài),并監(jiān)視更新安裝。 if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { traceBeginAndSlog("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); traceEnd(); } //跟蹤并緩存設備狀態(tài)。 mSystemServiceManager.startService(CachedDeviceStateService.class); // 跟蹤在Binder調用中花費的cpu時間 mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class); // 跟蹤handlers中處理messages所花費的時間。 mSystemServiceManager.startService(LooperStatsService.Lifecycle.class); //管理apk回滾 mSystemServiceManager.startService(RollbackManagerService.class); // 用于捕獲bugreport,adb bugreport 命令調用的就是這個服務 mSystemServiceManager.startService(BugreportManagerService.class); // 管理Gpu和Gpu驅動的服務 mSystemServiceManager.startService(GpuService.class); }
總結一下,核心服務共計9個:
服務名稱 | 描述 |
---|---|
BatteryService | 追蹤電池充電狀態(tài)和電量 |
UsageStatsManagerInternal | 跟蹤應用程序使用狀態(tài) |
WebViewUpdateService | 跟蹤可更新的WebView是否處于就緒狀態(tài),并監(jiān)視更新安裝。 |
CachedDeviceStateService | 跟蹤并緩存設備狀態(tài) |
BinderCallsStatsService | 跟蹤在Binder調用中花費的cpu時間 |
LooperStatsService | 跟蹤handlers中處理messages所花費的時間。 |
RollbackManagerService | 管理apk回滾 |
BugreportManagerService | 用于捕獲bugreport |
GpuService | 管理Gpu和Gpu驅動 |
startOtherServices
這個方法負責啟動剩下的服務,共計有70多個,限于篇幅的原因,在此不再一一列舉,貼一張從網(wǎng)上找到的圖片大家簡單的了解一下就行了:
需要注意的是在startOtherServices結尾處調用了AMS的systemReady方法,AMS的systemReady里有這樣一條語句:
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
這條語句會啟動如下的Intent:
Intent getHomeIntent() { Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); intent.setComponent(mTopComponent); intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { intent.addCategory(Intent.CATEGORY_HOME); } return intent; }
注意到Intent.CATEGORY_HOME沒,這意味著startHomeOnAllDisplays最終啟動的是android的launcher app,android的啟動已經(jīng)進入了結尾。
至此,我們從按下電源鍵開始,到最終呈現(xiàn)launcher頁面,整個啟動流程做了一個簡單的介紹。Android 10的啟動分析系列正篇到此結束,其中啟動過程中的一些細節(jié)知識點,我們今后再以番外的形式補充介紹,感謝大家的收看??!!
更多關于Android10 啟動SystemServer的資料請關注腳本之家其它相關文章!
相關文章
Android itemDecoration接口實現(xiàn)吸頂懸浮標題
這篇文章主要介紹了Android中使用itemdecoration實現(xiàn)吸頂懸浮標題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-11-11Android客戶端與服務端數(shù)據(jù)加密傳輸方案詳解
這篇文章主要為大家介紹了Android客戶端與服務端數(shù)據(jù)加密傳輸方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01Android RecyclerView 上拉加載更多及下拉刷新功能的實現(xiàn)方法
這篇文章主要介紹了Android RecyclerView 上拉加載更多及下拉刷新的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09