Android-SystemServer处理过程

SystemServer进程主要用于创建系统服务,AMS,WMS,PMS都是它创建的。
1624170053784.jpg

在ZygoteInit的startSystemServer方法中启动了SystemServer进程。因为SystemServer进程复制了Zygote进程的地址空间,因此也会得到Zygote进程创建的Socket。但是这个Socket对于SystemServer没有用处,所以会关掉这个Socket。最后会调用handleSystemServerProcess方法来启动SystemServer进程。

在handleSystemServerProcess方法中,会先创建PathClassLoader,然后调用ZygoteInit的zygoteInit方法。在zygoteInit方法中会调用nativeZygoteInit方法,这个是调用Native方法启动Binder线程池。这样SystemServer进程就可以使用Binder与其他进程进行通信了。然后会进入SystemServer的main方法。

启动Binder线程池

nativeZygoteInit方法对应的JNI文件是AndroidRuntime.cpp的com_android_internal_os_ZygoteInit_nativeZygoteInit函数。该函数最后回到用app_main.cpp中AndroidRuntime的onZygoteInit方法,会调用startThreadPool来启动Binder线程池。

SystemServer的main方法

在调用完了nativeZygote方法后,会调用RuntimeInit的applicationInit方法来进入SystemServer的main方法。

接着会调用RuntimeInit的invokeStaticMain方法,在这个方法中会先通过反射获取SystemServer类,反射时的className为com.android.server.SystemServer。然后找到SystemServer的main方法。然后将找到的main方法传入MethodAndArgsCaller异常中,并抛出该异常。捕获MethodAndArgsCaller异常的代码在ZygoteInit.java的main方法中,这个main方法会调用SystemServer的main方法

这个通过抛异常的方式来调用SystemServer的main方法是因为这个抛出异常的处理会清除所有的设置过程需要的堆栈帧,并让SystemServer的main方法看起来像SystemServer进程的入口方法。

在Zygote启动SystemServer后,SystemServer进程已经做了很多准备工作,这都是在main方法调用之前做的,这使得main方法看起来不像是SystemServer的入口方法。所以这样处理后main方法看起来像是SystemServer的入口方法。

在捕获到MethodAndArgsCaller异常后,回调用该异常的run方法。MethodAndArgsCaller是Zygote的静态内部类,并实现了Runnable方法,会在run方法中调用SystemServer的main方法。

main方法中只调用了一行代码:

new SystemServer().run();
复制代码

在run方法中会调用Looper.prepareMainLooper()方法,这个应该是系统的MainLooper。然后会加载libandroid_servers.so动态库,创建系统Context,创建SystemServiceManager并传入系统Context。在创建完了SystemServiceManager后添加到LocalServices的集合中。

接下来调用startBootstrapServices方法,用SystemServiceManager启动ActivityManagerService、PowerManagerService、PackageManagerService等服务。

然后调用startCoreServices方法启动DropBoxManagerService、BateryService、UsageStatsService和WebViewUpdateService。

最后在startOtherServices方法中启动CameraService、AleramManagerService、VrManagerService等服务。

这些服务的父类都是SystemService。

可以看出系统将服务分为了三种类型,分别是引导服务,核心服务和其他服务。其中其他服务是一些非紧要和不需要立即启动的服务。这些系统服务一共有100多个。

1624174021595.jpg

这些服务的启动逻辑是相似的,以PowerManagerService举例:

mPowerManagerService = mStstemServiceManager.startService(PowerManagerService.class)
复制代码

SystemServiceManager的startService方法启动了PowerManagerService。方法中将PowerManagerService添加到mServices中,mService是一个储存SystemService类型的ArrayList,这样就完成了PowerManagerService的注册工作。然后调用PowerManagerService的onStart函数,完成PowerManagerService启动。

除了mSystemServiceManager的startService函数启动系统服务外,也可以调用系统服务的main方法来启动服务。在main方法中会调用ServiceManager的addService方法注册到ServiceManager中。

ServiceManager是管理系统中的各种Service,用户系统C/S架构中的Binder通信机制。Client端需要使用某个Service,则需要先到ServiceManager查询Service的信息,然后根据Service的相关信息与Service所在的Server进程建立通信通路,这样Client就可以使用Service了。

SystemServer进程总结:

  • 启动Binder线程池
  • 创建SystemServiceManager,用于对系统的服务进行创建、启动和生命周期管理。
  • 启动各种服务
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享