SystemServer1createSystemContext11systemMain12getSystemContext1121createSystemContext2startBootstrapServices21setSystemPRocess3startCoreServices4startOtherServices總結(jié)那么大概又那些服務(wù)被啟動(dòng)了呢
SystemServer分成兩個(gè)部分,一部分是由ZygoteInit進(jìn)程啟動(dòng),一部分執(zhí)行SystemServer的main()方法啟動(dòng)
/** * 這個(gè)主方法從zygote進(jìn)程啟動(dòng). */ public static void main(String[] args) { new SystemServer().run(); }接下來我們就開始分析SystemServer的run()方法
private void run() { try { ... //對于時(shí)間的處理 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } ... //設(shè)置虛擬機(jī)庫路徑 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // 每個(gè)小時(shí)進(jìn)行一次性能統(tǒng)計(jì)輸出到文件中 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(); // 調(diào)整虛擬機(jī)堆內(nèi)存 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); ... //初始化主線程 Looper.prepareMainLooper(); // 裝在libandroid_servers.so // 注意在Android中庫的名稱都是lib+名稱+.so System.loadLibrary("android_servers"); ... // 創(chuàng)建ActivityThread并且創(chuàng)建系統(tǒng)的Context賦值給當(dāng)前類變量mSystemContext createSystemContext();//[1.1] // 創(chuàng)建SystemServiceManager的對象,此對象負(fù)責(zé)系統(tǒng)Service的啟動(dòng) mSystemServiceManager = new SystemServiceManager(mSystemContext); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); } finally { Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); } // 創(chuàng)建啟動(dòng)所有的java服務(wù) 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); } ... // 進(jìn)入消息處理的循環(huán) Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }@(SystemServer.java->createSystemContext())
創(chuàng)建ActivityThread對象和ContextImpl對象
private void createSystemContext() { ActivityThread activityThread = ActivityThread.systemMain();//[1.1.1]創(chuàng)建ActivityThread對象 mSystemContext = activityThread.getSystemContext();//[1.1.2]創(chuàng)建系統(tǒng)Context對象 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); }@(ActivityThread.java->systemMain())
創(chuàng)建ActivityThread對象,這個(gè)對象主要是負(fù)責(zé)管理四大組件,applicationThread等等
public static ActivityThread systemMain() { if (!ActivityManager.isHighEndGfx()) { ThreadedRenderer.disable(true); } else { ThreadedRenderer.enableForegroundTrimming(); } ActivityThread thread = new ActivityThread();//創(chuàng)建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);//創(chuàng)建ContextImpl對象 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(), context.mResourcesManager.getDisplayMetrics()); return context; }@(SystemServer.java->startBootstrapServices())
在這個(gè)方法中啟動(dòng)一些重要的service,這些服務(wù)支持system的正常運(yùn)行,但是又互相依賴,所以放到SystemServer中進(jìn)行集中初始化,如果自己的服務(wù)和這些服務(wù)有著密切的關(guān)系,要不然就要放到Installer中初始化.
private void startBootstrapServices() { /*通過反射構(gòu)造對象,并且調(diào)用將其添加到SystemServerManager中的ArrayList<SystemService>mServices中 并且調(diào)用對應(yīng)的service.onStart()方法,因?yàn)樗詓ervice繼承SystemService,其中需要實(shí)現(xiàn)onStart()方法*/ Installer installer = mSystemServiceManager.startService(Installer.class); // 對AMS進(jìn)行設(shè)置 mActivityManagerService = mSystemServiceManager.startService( ActivityManagerService.Lifecycle.class).getService(); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); // 電源管理服務(wù),由于其他服務(wù)可能今早的需要電源的管理,所以電源管理服務(wù)在比較前面的位置 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class); //...其他服務(wù)同理 // Only run "core" apps if we're encrypting the device. String cryptState = SystemProperties.get("vold.decrypt"); ... //添加PMS服務(wù)并且運(yùn)行 mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); ... //運(yùn)行UMS traceBeginAndSlog("StartUserManagerService"); mSystemServiceManager.startService(UserManagerService.LifeCycle.class); Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); //用于緩存應(yīng)用包資源 AttributeCache.init(mSystemContext); mActivityManagerService.setSystemProcess();//[1.2.1] startSensorService(); }@(ActivityManagerService.java->setSystemProcess())
添加一些Service,ServiceManager.addService的原理在深入理解Android:卷2中仔細(xì)說明,目前本人未能徹底搞清楚Binder,所以在這里,只是指導(dǎo)將服務(wù)添加到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())
啟動(dòng)一些核心服務(wù)
private void startCoreServices() { // 啟動(dòng)電源管理服務(wù) mSystemServiceManager.startService(BatteryService.class); // 跟蹤應(yīng)用程序使用情況統(tǒng)計(jì)信息。 mSystemServiceManager.startService(UsageStatsService.class); mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class)); //開啟WebView更新服務(wù) mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); }@(SystemServer.java->startOtherServices())
添加各式各樣的服務(wù)之后調(diào)用systemReady來啟動(dòng)
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開啟了那么多系統(tǒng)的服務(wù)并且啟動(dòng) - ActivityThread也是在此時(shí)創(chuàng)建的 - 主線程的Loop也是在這里創(chuàng)建的 - ContextImpl也是在這里創(chuàng)建的 - 創(chuàng)建你Application對象,并且調(diào)用對應(yīng)的onCreate()方法
EntropyService:熵(shang)服務(wù),用于產(chǎn)生隨機(jī)數(shù) PowerManagerService:電源管理服務(wù) ActivityManage搜索rService:最核心服務(wù)之一,Activity管理服務(wù) TelephonyRegistry:電話服務(wù),電話底層通知服務(wù) PackageManagerService:程序包管理服務(wù) AccountManagerService:聯(lián)系人帳戶管理服務(wù) ContentService:內(nèi)容提供器的服務(wù),提供跨進(jìn)程數(shù)據(jù)交換 LightsService:光感應(yīng)傳感器服務(wù) BatteryService:電池服務(wù),當(dāng)電量不足時(shí)發(fā)廣播 VibratorService:震動(dòng)器服務(wù) AlarmManagerService:鬧鐘服務(wù) WindowManagerService:窗口管理服務(wù) BluetoothService:藍(lán)牙服務(wù) InputMethodManagerService:輸入法服務(wù),打開關(guān)閉輸入法 accessibilityManagerService:輔助管理程序截獲所有的用戶輸入,并根據(jù)這些輸入給用戶一些額外的反饋,起到輔助的效果,View的點(diǎn)擊、焦點(diǎn)等事件分發(fā)管理服務(wù) DevicePolicyManagerService:提供一些系統(tǒng)級(jí)別的設(shè)置及屬性 StatusBarManagerService:狀態(tài)欄管理服務(wù) ClipboardService:粘貼板服務(wù) NetworkManagementService:手機(jī)網(wǎng)絡(luò)管理服務(wù) TextServicesManagerService: NetworkStatsService:手機(jī)網(wǎng)絡(luò)狀態(tài)服務(wù) NetworkPolicyManagerService: WifiP2pService:Wifi點(diǎn)對點(diǎn)直聯(lián)服務(wù) WifiService:WIFI服務(wù) ConnectivityService:網(wǎng)絡(luò)連接狀態(tài)服務(wù) ThrottleService:modem節(jié)流閥控制服務(wù) MountService:磁盤加載服務(wù),通常也mountd和vold服務(wù)結(jié)合 NotificationManagerService:通知管理服務(wù),通常和StatusBarManagerService DeviceStorageMonitorService:存儲(chǔ)設(shè)備容量監(jiān)聽服務(wù) LocationManagerService:位置管理服務(wù) CountryDetectorService:檢查當(dāng)前用戶所在的國家 SearchManagerService:搜索管理服務(wù) DropBoxManagerService:系統(tǒng)日志文件管理服務(wù)(大部分程序錯(cuò)誤信息) WallpaperManagerService:壁紙管理服務(wù) AudioService:AudioFlinger上層的封裝的音量控制管理服務(wù) UsbService:USB Host和device管理服務(wù) UiModeManagerService:UI模式管理服務(wù),監(jiān)聽車載、座機(jī)等場合下UI的變化 BackupManagerService:備份服務(wù) AppWidgetService:應(yīng)用桌面部件服務(wù) RecognitionManagerService:身份識(shí)別服務(wù) DiskStatsService:磁盤統(tǒng)計(jì)服務(wù) SamplingProfilerService:性能統(tǒng)計(jì)服務(wù) NetworkTimeUpdateService:網(wǎng)絡(luò)時(shí)間更新服務(wù)
 
  | 
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注