简介
在可以使用 AIDL 进行进程间通信后,AIDL 是基于 Binder 的,来通过 AIDL 分析一下 Binder。
使用 AIDL 的过程中会有这样的疑问:
Server onBind 方法返回的是一个 IMyInterface.Stub 对象,为什么客户端接收到的是 BinderProxy 对象呢
首先对过程中出现的类进行解释
IMyInterface : 自定义的 AIDL 接口,实现了 IInterface 接口;
IMyInterface$Stub : IMyInterface 的内部类,继承 Binder, 实现了 IMyInterface 接口,Service 中返回的就是自己实现的这个对象,重写了它的里面自定义 AIDL 的方法;
IMyInterface$Stub$Proxy : Stub 的内部类,封装了 Binder 对象
BinderProxy : Binder 的内部类,进程间通信时传递的类型
方法的解释
IMyInterface$Stub.asInterface : 如果是相同进程,则返回该对象,不同进程就是把对象封装成 BinderProxy
客户端获取服务端的对象
- 客户端 binderService, 服务端 Service onBind 方法返回了一个 Stub 对象,当这一过程是跨进程时,返回的 Stub 对象会被封装成 BinderProxy 对象,调用 ServiceConnection.onServiceConnected 作为参数传递,具体可以看下面这张 bindServie 流程图,在 ActivityManagerNative.onTransact 中会把 IMyInterface S t u b 封 装 一 下 , I S e r v i c e C o n n e