SystemServer1createSystemContext11systemMain12getSystemContext1121createSystemContext2startBootstrapServices21setSystemPRocess3startCoreServices4startOtherServices總結那么大概又那些服務被啟動了呢
SystemServer分成兩個部分,一部分是由ZygoteInit進程啟動,一部分執行SystemServer的main()方法啟動
/** * 這個主方法從zygote進程啟動. */ public static void main(String[] args) { new SystemServer().run(); }接下來我們就開始分析SystemServer的run()方法
private void run() { try { ... //對于時間的處理 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } ... //設置虛擬機庫路徑 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // 每個小時進行一次性能統計輸出到文件中 if (SamplingProfilerIntegration.isEnabled()) { SamplingProfilerIntegration.start(); mProfilerSnapshotTimer = new Timer(); mProfilerSnapshotTimer.schedule(new TimerTask() { @Override public void run() { SamplingProfilerIntegration.writeSnapshot("system_server", null); } }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL); } // Mmmmmm... more memory! VMRuntime.getRuntime().clearGrowthLimit(); // 調整虛擬機堆內存 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); ... //初始化主線程 Looper.prepareMainLooper(); // 裝在libandroid_servers.so // 注意在Android中庫的名稱都是lib+名稱+.so System.loadLibrary("android_servers"); ... // 創建ActivityThread并且創建系統的Context賦值給當前類變量mSystemContext createSystemContext();//[1.1] // 創建SystemServiceManager的對象,此對象負責系統Service的啟動 mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } // 創建啟動所有的java服務 try { Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices"); startBootstrapServices();//[1.2] startCoreServices();.//[1.3] startOtherServices();//[1.4] } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } ... // 進入消息處理的循環 Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }@(SystemServer.java->createSystemContext())
創建ActivityThread對象和ContextImpl對象
private void createSystemContext() { ActivityThread activityThread = ActivityThread.systemMain();//[1.1.1]創建ActivityThread對象 mSystemContext = activityThread.getSystemContext();//[1.1.2]創建系統Context對象 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); }@(ActivityThread.java->systemMain())
創建ActivityThread對象,這個對象主要是負責管理四大組件,applicationThread等等
public static ActivityThread systemMain() { if (!ActivityManager.isHighEndGfx()) { ThreadedRenderer.disable(true); } else { ThreadedRenderer.enableForegroundTrimming(); } ActivityThread thread = new ActivityThread();//創建ActivityThread對象 thread.attach(true); return thread; }@(ActivityThread.java->getSystemContext())
public ContextImpl getSystemContext() { synchronized (this) { if (mSystemContext == null) { mSystemContext = ContextImpl.createSystemContext(this);//[1.1.2.1] } return mSystemContext; } }@(ContextImpl.java->createSystemContext())
static ContextImpl createSystemContext(ActivityThread mainThread) { LoadedApk packageInfo = new LoadedApk(mainThread); ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, 0, null, null, Display.INVALID_DISPLAY);//創建ContextImpl對象 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(), context.mResourcesManager.getDisplayMetrics()); return context; }@(SystemServer.java->startBootstrapServices())
在這個方法中啟動一些重要的service,這些服務支持system的正常運行,但是又互相依賴,所以放到SystemServer中進行集中初始化,如果自己的服務和這些服務有著密切的關系,要不然就要放到Installer中初始化.
private void startBootstrapServices() { /*通過反射構造對象,并且調用將其添加到SystemServerManager中的ArrayList<SystemService>mServices中 并且調用對應的service.onStart()方法,因為所以service繼承SystemService,其中需要實現onStart()方法*/ Installer installer = mSystemServiceManager.startService(Installer.class); // 對AMS進行設置 mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); // 電源管理服務,由于其他服務可能今早的需要電源的管理,所以電源管理服務在比較前面的位置 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); //...其他服務同理 // Only run "core" apps if we're encrypting the device. String cryptState = SystemProperties.get("vold.decrypt"); ... //添加PMS服務并且運行 mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); ... //運行UMS traceBeginAndSlog("StartUserManagerService"); mSystemServiceManager.startService(UserManagerService.LifeCycle.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); //用于緩存應用包資源 AttributeCache.init(mSystemContext); mActivityManagerService.setSystemProcess();//[1.2.1] startSensorService(); }@(ActivityManagerService.java->setSystemProcess())
添加一些Service,ServiceManager.addService的原理在深入理解Android:卷2中仔細說明,目前本人未能徹底搞清楚Binder,所以在這里,只是指導將服務添加到native層就好.
public void setSystemProcess() { try { ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); ServiceManager.addService("meminfo", new MemBinder(this)); ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); ServiceManager.addService("dbinfo", new DbBinder(this)); if (MONITOR_CPU_USAGE) { ServiceManager.addService("cpuinfo", new CpuBinder(this)); } ServiceManager.addService("permission", new PermissionController(this)); ServiceManager.addService("processinfo", new ProcessInfoService(this)); ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY); mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); synchronized (this) { ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); app.persistent = true; app.pid = MY_PID; app.maxAdj = ProcessList.SYSTEM_ADJ; app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); synchronized (mPidsSelfLocked) { mPidsSelfLocked.put(app.pid, app); } updateLruProcessLocked(app, false, null); updateOomAdjLocked(); } } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException( "Unable to find android system package", e); } }@(SystemServer.java->startCoreServices())
啟動一些核心服務
private void startCoreServices() { // 啟動電源管理服務 mSystemServiceManager.startService(BatteryService.class); // 跟蹤應用程序使用情況統計信息。 mSystemServiceManager.startService(UsageStatsService.class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); //開啟WebView更新服務 mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); }@(SystemServer.java->startOtherServices())
添加各式各樣的服務之后調用systemReady來啟動
private void startOtherServices() { ... contentService = ContentService.main(context, mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL); mActivityManagerService.installSystemProviders(); vibrator = new VibratorService(context); ServiceManager.addService("vibrator", vibrator); consumerIr = new ConsumerIrService(context); ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr); mAlarmManagerService = mSystemServiceManager.startService(AlarmManagerService.class); alarm = IAlarmManager.Stub.asInterface( ServiceManager.getService(Context.ALARM_SERVICE)); final Watchdog watchdog = Watchdog.getInstance(); watchdog.init(context, mActivityManagerService); ... mActivityManagerService.systemReady(new Runnable() { @Override public void run() { Slog.i(TAG, "Making services ready"); mSystemServiceManager.startBootPhase( SystemService.PHASE_ACTIVITY_MANAGER_READY); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady"); Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes"); try { mActivityManagerService.startObservingNativeCrashes(); } catch (Throwable e) { reportWtf("observing native crashes", e); } ... } });}原來SystemServer開啟了那么多系統的服務并且啟動 - ActivityThread也是在此時創建的 - 主線程的Loop也是在這里創建的 - ContextImpl也是在這里創建的 - 創建你Application對象,并且調用對應的onCreate()方法
EntropyService:熵(shang)服務,用于產生隨機數 PowerManagerService:電源管理服務 ActivityManage搜索rService:最核心服務之一,Activity管理服務 TelephonyRegistry:電話服務,電話底層通知服務 PackageManagerService:程序包管理服務 AccountManagerService:聯系人帳戶管理服務 ContentService:內容提供器的服務,提供跨進程數據交換 LightsService:光感應傳感器服務 BatteryService:電池服務,當電量不足時發廣播 VibratorService:震動器服務 AlarmManagerService:鬧鐘服務 WindowManagerService:窗口管理服務 BluetoothService:藍牙服務 InputMethodManagerService:輸入法服務,打開關閉輸入法 accessibilityManagerService:輔助管理程序截獲所有的用戶輸入,并根據這些輸入給用戶一些額外的反饋,起到輔助的效果,View的點擊、焦點等事件分發管理服務 DevicePolicyManagerService:提供一些系統級別的設置及屬性 StatusBarManagerService:狀態欄管理服務 ClipboardService:粘貼板服務 NetworkManagementService:手機網絡管理服務 TextServicesManagerService: NetworkStatsService:手機網絡狀態服務 NetworkPolicyManagerService: WifiP2pService:Wifi點對點直聯服務 WifiService:WIFI服務 ConnectivityService:網絡連接狀態服務 ThrottleService:modem節流閥控制服務 MountService:磁盤加載服務,通常也mountd和vold服務結合 NotificationManagerService:通知管理服務,通常和StatusBarManagerService DeviceStorageMonitorService:存儲設備容量監聽服務 LocationManagerService:位置管理服務 CountryDetectorService:檢查當前用戶所在的國家 SearchManagerService:搜索管理服務 DropBoxManagerService:系統日志文件管理服務(大部分程序錯誤信息) WallpaperManagerService:壁紙管理服務 AudioService:AudioFlinger上層的封裝的音量控制管理服務 UsbService:USB Host和device管理服務 UiModeManagerService:UI模式管理服務,監聽車載、座機等場合下UI的變化 BackupManagerService:備份服務 AppWidgetService:應用桌面部件服務 RecognitionManagerService:身份識別服務 DiskStatsService:磁盤統計服務 SamplingProfilerService:性能統計服務 NetworkTimeUpdateService:網絡時間更新服務
新聞熱點
疑難解答