1 ActivityManagerService.setSystemProcess()
2 ServiceManager.addService![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TgaPM2H4-1619575780715)(/home/lxr/.config/Typora/typora-user-images/image-20210425112347083.png)]](https://img-blog.csdnimg.cn/20210428101103355.png)
getIServiceManager()返回的是什么对象?怎样得到的呢?
2.1 getIServiceManager()
getIServiceManager返回的是接口IServiceManager的实现类
2.2 如何得到实现类
1)asInterface
以obj为参数,创建一个ServiceManagerProxy对象.ServiceManagerProxy对象中的各个函数会将相应的请求打包后交给BpProxy对象,最终BpProxy对象发送给Binder驱动完成一次通信.
2)Binder.allowBlocking
用来覆盖setWarnOnBlocking的值
3)BinderInternal.getContextObject()
getContextObject()是一个native方法,其实现是android_util_Binder.cpp中的android_os_BinderInternal_getContextObject
a) ProcessState::self()->getContextObject(NULL),返回的是一个BpProxy对象,其中的NULL指定Proxy通信的目的端是ServiceManager.
b) javaObjectForIBinder,通过Native的BpProxy对象创建一个java的BinderProxy对象;并将Native层的BpProxy对象指针保存到BinderProxy对象的成员对象nativeData中的mObject中,这样BinderProxy对象的Native方法可以通过mObject获取BpProxy对象的指针,而该BpProxy对象的通信目标是ServiceManager
总结:BinderInternal.getContextObject()=new BinderProxy();getIServiceManager()=new ServiceManagerProxy(new BinderProxy() ).
3 ServiceManagerProxy.addService()
4 BinderProxy.transact()
5 BinderProxy.transactNative()
transactNative方法是一个native方法,其实现是android_util_Binder.cpp中的android_os_BinderProxy_transact方法
6 android_util_Binder.android_os_BinderProxy_transact()
6.1 将传入的java层的Parcel转成Native层的Parcel对象
data是传入的参数的Parcel,reply是用于接收回复的Parcel
6.2 从java的BinderProxy对象中获取Native层的BpProxy对象
6.3 通过Native层的BpProxy对象将请求发送给ServiceManager
总结:java层的binder最终是借助Native层的binder与service进行通信
7 总结
Binder通信的目的是:将客户端的请求发送到Binder分区,并将Binder分区中请求的结果传回客户端,而作为Binder核心ServiceManager是直接与Binder分区进行交互,读取并处理请求.即打开binder设备,然后读请求和写回复.