日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
系統(tǒng)中的大管家—SystemServer進(jìn)程

 

本文轉(zhuǎn)載自微信公眾號(hào)「碼上積木」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系碼上積木公眾號(hào)。

前言

上篇說(shuō)到Android系統(tǒng)的啟動(dòng)流程,Zygote進(jìn)程fork的第一個(gè)進(jìn)程就是SystemServer進(jìn)程。

這個(gè)進(jìn)程負(fù)責(zé)啟動(dòng)和管理JavaFramework層,也就是提供了框架層的很多服務(wù),比如我們熟知的AMS,PMS,WMS,還有DisplayManagerService、CameraService等等,也就是說(shuō)它掌握了Android系統(tǒng)中的命脈,是Android系統(tǒng)中的大管家。

一起瞅瞅吧~

(本文源碼基于Android9.0)

誕生

之前在Android系統(tǒng)的啟動(dòng)過(guò)程中???說(shuō)到,SystemServer進(jìn)程是由Zygote進(jìn)程fork而來(lái)。

fork()函數(shù)通過(guò)系統(tǒng)調(diào)用創(chuàng)建一個(gè)與原來(lái)進(jìn)程幾乎完全相同的進(jìn)程,可以理解為COPY了一個(gè)進(jìn)程出來(lái),而這個(gè)新進(jìn)程就是它的子進(jìn)程。

而關(guān)于SystemServer的誕生,還要從ZygoteInit的forkSystemServer方法說(shuō)起...(只保留主要代碼)

 
 
 
 
  1. private static Runnable forkSystemServer(String abiList, String socketName, 
  2.            ZygoteServer zygoteServer) { 
  3.        //...  
  4.  
  5.        // 1 
  6.        int pid; 
  7.        pid = Zygote.forkSystemServer( 
  8.                    parsedArgs.uid, parsedArgs.gid, 
  9.                    parsedArgs.gids, 
  10.                    parsedArgs.runtimeFlags, 
  11.                    null, 
  12.                    parsedArgs.permittedCapabilities, 
  13.                    parsedArgs.effectiveCapabilities); 
  14.  
  15.        /* For child process */ 
  16.        if (pid == 0) { 
  17.            //2 
  18.            zygoteServer.closeServerSocket(); 
  19.            //3 
  20.            return handleSystemServerProcess(parsedArgs); 
  21.        } 
  22.  
  23.        return true; 
  24.    } 
  25.  
  26.    /** 
  27.     * Finish remaining work for the newly forked system server process. 
  28.     */ 
  29.    private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) { 
  30.  
  31.            //...  
  32.  
  33.            /* 
  34.             * Pass the remaining arguments to SystemServer. 
  35.             */ 
  36.            ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl); 
  37.    } 
  38.  
  39.  
  40.    public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) { 
  41.        //... 
  42.  
  43.     //4  
  44.        RuntimeInit.commonInit(); 
  45.        //5 
  46.        ZygoteInit.nativeZygoteInit(); 
  47.        //6 
  48.        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); 
  49.    } 

startSystemServer方法中:

  • 1、調(diào)用forkSystemServer方法創(chuàng)建了子進(jìn)程——SystemServer進(jìn)程。
  • 2、fork之后,這里判斷了fork的返回值pid是否等于0,如果等于0,就代表fork成功,就處在SystemServer進(jìn)程中了。然后關(guān)閉了從Zygote進(jìn)程fork帶來(lái)的Socket對(duì)象。
  • 3、然后調(diào)用了handleSystemServerProcess方法,并最終走到zygoteInit,做了一些新進(jìn)程的初始化工作。

zygoteInit方法中:

  • 4、commonInit方法就是做了一些進(jìn)程通用的初始化工作,比如設(shè)置時(shí)區(qū),重置log配置。
  • 5、nativeZygoteInit方法通過(guò)JNI會(huì)走到native層,主要的工作就是創(chuàng)建了新的Binder線程池,這樣SystemServer才能和各大app進(jìn)程進(jìn)行通信。
  • 6、applicationInit方法,最終會(huì)走到findStaticMain方法中,通過(guò)反射調(diào)用SystemServer類的main方法,簡(jiǎn)單貼下代碼:
 
 
 
 
  1. protected static Runnable findStaticMain(String className, String[] argv, 
  2.            ClassLoader classLoader) { 
  3.        Class cl; 
  4.  
  5.        try { 
  6.            cl = Class.forName(className, true, classLoader); 
  7.        }  
  8.        //... 
  9.  
  10.        Method m; 
  11.        try { 
  12.            m = cl.getMethod("main", new Class[] { String[].class }); 
  13.        }  
  14.        //... 
  15.       
  16.        return new MethodAndArgsCaller(m, argv); 
  17.    } 

工作

SystemServer進(jìn)程創(chuàng)建出來(lái)了,并且做了一些初始化工作,接下來(lái)就來(lái)到了main方法了,顧名思義,肯定要開(kāi)始正經(jīng)主要的工作了。

 
 
 
 
  1. public static void main(String[] args) { 
  2.         new SystemServer().run(); 
  3.     } 
  4.  
  5.  
  6.     private void run() { 
  7.         try { 
  8.             //... 
  9.  
  10.             // 1 
  11.             android.os.Process.setThreadPriority( 
  12.                 android.os.Process.THREAD_PRIORITY_FOREGROUND); 
  13.             android.os.Process.setCanSelfBackground(false); 
  14.  
  15.             Looper.prepareMainLooper(); 
  16.             Looper.getMainLooper().setSlowLogThresholdMs( 
  17.                     SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); 
  18.  
  19.             // 2 
  20.             System.loadLibrary("android_servers"); 
  21.  
  22.             // 3 
  23.             performPendingShutdown(); 
  24.  
  25.             // 4 
  26.             createSystemContext(); 
  27.  
  28.             // 5 
  29.             mSystemServiceManager = new SystemServiceManager(mSystemContext); 
  30.             mSystemServiceManager.setStartInfo(mRuntimeRestart, 
  31.                     mRuntimeStartElapsedTime, mRuntimeStartUptime); 
  32.             LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); 
  33.             // Prepare the thread pool for init tasks that can be parallelized 
  34.             SystemServerInitThreadPool.get(); 
  35.         } finally { 
  36.             traceEnd();  
  37.         } 
  38.  
  39.         //... 
  40.  
  41.         // Start services. 
  42.         try { 
  43.             //6 
  44.             startBootstrapServices(); 
  45.             //7 
  46.             startCoreServices(); 
  47.             //8 
  48.             startOtherServices(); 
  49.             SystemServerInitThreadPool.shutdown(); 
  50.         }  
  51.  
  52.         //... 
  53.  
  54.         // Loop forever. 
  55.         Looper.loop(); 
  56.         throw new RuntimeException("Main thread loop unexpectedly exited"); 
  57.     }     
  • 1、準(zhǔn)備主線程,Looper。
  • 2、加載動(dòng)態(tài)庫(kù)。
  • 3、檢測(cè)上次關(guān)機(jī)過(guò)程是否失敗。
  • 4、初始化系統(tǒng)上下文。
 
 
 
 
  1. private void createSystemContext() { 
  2.         ActivityThread activityThread = ActivityThread.systemMain(); 
  3.         mSystemContext = activityThread.getSystemContext(); 
  4.         mSystemContext.setTheme(DEFAULT_SYSTEM_THEME); 
  5.  
  6.         final Context systemUiContext = activityThread.getSystemUiContext(); 
  7.         systemUiContext.setTheme(DEFAULT_SYSTEM_THEME); 
  8.     } 

在這個(gè)方法中,創(chuàng)建了ActivityThread類,獲取了上下文,并設(shè)置了一些系統(tǒng)主題。

  • 5、創(chuàng)建SystemServiceManager,用于后續(xù)的系統(tǒng)服務(wù)管理創(chuàng)建等工作。

run方法最后的工作就是啟動(dòng)三個(gè)服務(wù)類型的服務(wù),也是我們重點(diǎn)關(guān)注的,分別是引導(dǎo)服務(wù),核心服務(wù),其他服務(wù)。

這些服務(wù)一共有100多個(gè),關(guān)系著Android整個(gè)應(yīng)用生態(tài),下面我們具體說(shuō)下。

  • 6、啟動(dòng)引導(dǎo)服務(wù)
 
 
 
 
  1. private void startBootstrapServices() { 
  2.  
  3.         //安裝APK服務(wù) 
  4.         traceBeginAndSlog("StartInstaller"); 
  5.         Installer installer = mSystemServiceManager.startService(Installer.class); 
  6.         traceEnd(); 
  7.  
  8.         //AMS,負(fù)責(zé)四大組件的啟動(dòng)調(diào)度等工作 
  9.         mActivityManagerService = mSystemServiceManager.startService( 
  10.                 ActivityManagerService.Lifecycle.class).getService(); 
  11.         mActivityManagerService.setSystemServiceManager(mSystemServiceManager); 
  12.         mActivityManagerService.setInstaller(installer); 
  13.         traceEnd(); 
  14.  
  15.  
  16.         // 管理和顯示背光LED等服務(wù) 
  17.         traceBeginAndSlog("StartLightsService"); 
  18.         mSystemServiceManager.startService(LightsService.class); 
  19.         traceEnd(); 
  20.  
  21.         //PMS,負(fù)責(zé)APK安裝,解析卸載等工作 
  22.         traceBeginAndSlog("StartPackageManagerService"); 
  23.         mPackageManagerService = PackageManagerService.main(mSystemContext, installer, 
  24.                 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); 
  25.         mFirstBoot = mPackageManagerService.isFirstBoot(); 
  26.         mPackageManager = mSystemContext.getPackageManager(); 
  27.         traceEnd(); 
  28.  
  29.         //... 
  30.  
  31.     } 

引導(dǎo)服務(wù)中,有幾個(gè)我們畢竟熟悉的,比如AMS、PMS。

  • 7、啟動(dòng)核心服務(wù)
 
 
 
 
  1. private void startCoreServices() { 
  2.         traceBeginAndSlog("StartBatteryService"); 
  3.         // 管理電池相關(guān)服務(wù) 
  4.         mSystemServiceManager.startService(BatteryService.class); 
  5.         traceEnd(); 
  6.  
  7.         // 收集用戶使用時(shí)長(zhǎng)服務(wù) 
  8.         traceBeginAndSlog("StartUsageService"); 
  9.         mSystemServiceManager.startService(UsageStatsService.class); 
  10.         mActivityManagerService.setUsageStatsManager( 
  11.                 LocalServices.getService(UsageStatsManagerInternal.class)); 
  12.         traceEnd(); 
  13.  
  14.         // Webview更新服務(wù) 
  15.         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) { 
  16.             traceBeginAndSlog("StartWebViewUpdateService"); 
  17.             mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class); 
  18.             traceEnd(); 
  19.         } 
  20.  
  21.         //... 
  22.     } 
  • 8、啟動(dòng)其他服務(wù)
 
 
 
 
  1. private void startOtherServices() { 
  2.    //... 
  3.   
  4.             //電話管理服務(wù) 
  5.             traceBeginAndSlog("StartTelephonyRegistry"); 
  6.             telephonyRegistry = new TelephonyRegistry(context); 
  7.             ServiceManager.addService("telephony.registry", telephonyRegistry); 
  8.             traceEnd();     
  9.  
  10.  
  11.             //WMS,窗口管理服務(wù),也是打交道比較多的 
  12.             traceBeginAndSlog("StartWindowManagerService"); 
  13.             ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE); 
  14.             mSensorServiceStart = null; 
  15.             wm = WindowManagerService.main(context, inputManager, 
  16.                     mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, 
  17.                     !mFirstBoot, mOnlyCore, new PhoneWindowManager()); 
  18.             ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false, 
  19.                     DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); 
  20.             ServiceManager.addService(Context.INPUT_SERVICE, inputManager, 
  21.                     /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL); 
  22.             traceEnd(); 
  23.  
  24.  
  25.             //輸入事件管理服務(wù) 
  26.             traceBeginAndSlog("StartInputManager"); 
  27.             inputManager.setWindowManagerCallbacks(wm.getInputMonitor()); 
  28.             inputManager.start(); 
  29.             traceEnd();      
  30.  
  31.             //...      

啟動(dòng)了這么多服務(wù),我們?cè)倏匆幌路?wù)都是怎么具體啟動(dòng)的:

 
 
 
 
  1. public  T startService(Class serviceClass) { 
  2.        try { 
  3.            final String name = serviceClass.getName(); 
  4.  
  5.            // Create the service. 
  6.            final T service; 
  7.            try { 
  8.                Constructor constructor = serviceClass.getConstructor(Context.class); 
  9.                service = constructor.newInstance(mContext); 
  10.            } //... 
  11.            startService(service); 
  12.            return service; 
  13.        } finally { 
  14.            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER); 
  15.        } 
  16.    } 
  17.  
  18.    // 所有系統(tǒng)服務(wù)的集合 
  19.    private final ArrayList mServices = new ArrayList();     
  20.  
  21.    public void startService(@NonNull final SystemService service) { 
  22.        // Register it. 
  23.        mServices.add(service); 
  24.        // Start it. 
  25.        long time = SystemClock.elapsedRealtime(); 
  26.        try { 
  27.            service.onStart(); 
  28.        } catch (RuntimeException ex) { 
  29.            throw new RuntimeException("Failed to start service " + service.getClass().getName() 
  30.                    + ": onStart threw an exception", ex); 
  31.        } 
  32.        warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart"); 
  33.    } 

可以看到,首先通過(guò)反射創(chuàng)建了對(duì)應(yīng)的Service類,然后把對(duì)應(yīng)的Service加入到mServices集合中,完成注冊(cè)。然后調(diào)用onStart方法啟動(dòng)對(duì)應(yīng)的Service,完成初始化工作。

到這里,SystemServer的啟動(dòng)工作就完成了,再來(lái)回顧下,這個(gè)過(guò)程,到底干了些啥?

  • 首先,Zygote fork了SystemServer這個(gè)子進(jìn)程,然后關(guān)閉了原有的socket,創(chuàng)建了新的Binder線程池。
  • 其次,做了一些初始化工作,創(chuàng)建了Context對(duì)象,創(chuàng)建了SystemServiceManager類,用于管理所有的系統(tǒng)服務(wù)。
  • 最后,啟動(dòng)了三類系統(tǒng)服務(wù),分別是引導(dǎo)服務(wù),核心服務(wù)和其他服務(wù)。

體系知識(shí)延伸

Socket和Binder

我們注意到,在SystemServer被fork出來(lái)之后,做了一個(gè)操作就是關(guān)閉了Sokcet,啟動(dòng)了Binder線程池用于進(jìn)程間通信。問(wèn)題來(lái)了,為啥Zygote進(jìn)程是用Socket通信,而SystemServer進(jìn)程是用Binder進(jìn)行通信呢?

其實(shí)這是兩個(gè)問(wèn)題,第一個(gè)問(wèn)題是問(wèn)為什么Android獲取系統(tǒng)服務(wù)是用的Binder進(jìn)程通信呢?

這就涉及到Binder的知識(shí)點(diǎn)了,Binder之所以被設(shè)計(jì)出來(lái),就是因?yàn)樗袇^(qū)別于其他IPC方式的兩大優(yōu)點(diǎn):

  • 性能高,效率高:傳統(tǒng)的IPC(套接字、管道、消息隊(duì)列)需要拷貝兩次內(nèi)存、Binder只需要拷貝一次內(nèi)存、共享內(nèi)存不需要拷貝內(nèi)存。
  • 安全性好:接收方可以從數(shù)據(jù)包中獲取發(fā)送發(fā)的進(jìn)程Id和用戶Id,方便驗(yàn)證發(fā)送方的身份,其他IPC想要實(shí)驗(yàn)只能夠主動(dòng)存入,但是這有可能在發(fā)送的過(guò)程中被修改。

第二個(gè)問(wèn)題就是,為什么Zygote進(jìn)程不用Binder而用Socket通信呢?這也是wanAndroid中的一個(gè)問(wèn)題:

每日一問(wèn) | Activity啟動(dòng)流程中,大部分都是用Binder通訊,為啥跟Zygote通信的時(shí)候要用socket呢?(https://www.wanandroid.com/wenda/show/10482)

評(píng)論區(qū)主要有以下觀點(diǎn):

  • ServiceManager不能保證在zygote起來(lái)的時(shí)候已經(jīng)初始化好,所以無(wú)法使用Binder。
  • Socket 的所有者是 root,只有系統(tǒng)權(quán)限用戶才能讀寫,多了安全保障。
  • Binder工作依賴于多線程,但是fork的時(shí)候是不允許存在多線程的,多線程情況下進(jìn)程fork容易造成死鎖,所以就不用Binder了。

Binder線程池

Binder線程池到底是什么?之前有讀者也問(wèn)過(guò)類似的問(wèn)題。

Binder線程池位于服務(wù)端,它的主要作用就是將每個(gè)業(yè)務(wù)模塊的Binder請(qǐng)求統(tǒng)一轉(zhuǎn)發(fā)到遠(yuǎn)程Servie中去執(zhí)行,從而避免了重復(fù)創(chuàng)建Service的過(guò)程。也就是服務(wù)端只有一個(gè),但是可以處理多個(gè)不同客戶端的Binder請(qǐng)求。

AMS,PMS,WMS

在SystemServer進(jìn)程啟動(dòng)的過(guò)程中,也啟動(dòng)了很多系統(tǒng)服務(wù),其中就包括和應(yīng)用交互比較多的三個(gè)服務(wù):

  • AMS,ActivityManagerService,負(fù)責(zé)四大組件的啟動(dòng),切換,調(diào)度工作。
  • PMS,PackageManagerService,負(fù)責(zé)APK的安裝,解析,卸載工作。
  • WMS,WindowManagerService,負(fù)責(zé)窗口啟動(dòng),添加,刪除等工作。

參考

《Android進(jìn)階解密》 https://www.wanandroid.com/wenda/show/10482 https://blog.csdn.net/yiranfeng/article/details/103550262


新聞名稱:系統(tǒng)中的大管家—SystemServer進(jìn)程
路徑分享:http://www.5511xx.com/article/dppiooe.html