package vivo.testaidl; /** * Created by chenlong on 2019/1/31. */ import android.util.Log; /** * Stub 的几个关键内容介绍: * 构造函数 * 调用了 attachInterface() 方法 * 将一个描述符、特定的 IAidlInterface 与当前 Binder 绑定起来,这样后续调用 queryLocalInterface 就可以拿到这个 * 这里使用一个 DESCRIPTOR,一般是类的具体路径名,来做key ,用于唯一表示这个 IAidlInterface * onTransact() * Binder 关键的处理事物方法 * 根据传入的 code,调用本地/服务端的不同方法 * AIDL是一个典型的远程代理模式 */ public class AidlInterfaceBinderStub extends android.os.Binder { /** * 我们知道在跨进程通信中Binder对象是携带着IAidlInterface所定义的功能的 * 但是Binder通信机制中那么多Binder都有Interface。那么系统怎么识别哪个Binder是哪个Binder呢? * 所以IAidlInterface只是一个能力的抽象,DESCRIPTOR就是来表示具体是哪一个功能Interface。 */ public static final String DESCRIPTOR = "vivo.testaidl.IAidlInterface" ; public static final String TAG = "TAG_IAidlInterface" ; private IAidlInterface mAidlInterface = null ; /** * Construct the stub at attach it to the interface. * 在Binder内部保存mAidlInterface作为自己的owner * 和这个功能更对应的唯一描述descriptor,方便在通信的时候寻找。 */ public AidlInterfaceBinderStub(IAidlInterface mAidlInterface) { Log.d(AidlInterfaceBinderStub.TAG, "AidlInterfaceBinderStub---init AidlInterfaceBinderStub = " + this + " mAidlInterface = " + mAidlInterface); this .mAidlInterface = mAidlInterface; this .attachInterface(mAidlInterface, DESCRIPTOR); } @Override public boolean onTransact( int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { // 如果不在同一个进程, // 那么参数是被序列化后传过来的,所以这个方法是用来对入参做反序列化,并对返回值做序列化的 switch (code) { case INTERFACE_TRANSACTION: { Log.d(AidlInterfaceBinderStub.TAG, "AidlInterfaceBinderStub---onTransact--- INTERFACE_TRANSACTION---" + this ); reply.writeString(DESCRIPTOR); return true ; } case TRANSACTION_addition: { Log.d(AidlInterfaceBinderStub.TAG, "AidlInterfaceBinderStub---onTransact--- TRANSACTION_addition----" + this ); data.enforceInterface(DESCRIPTOR); int _arg0; _arg0 = data.readInt(); int _arg1; _arg1 = data.readInt(); // 调用 mAidlInterface的addition 方法,这个方法的实现是在服务端是 mAidlInterface服务端new出来的 int _result = mAidlInterface.addition(_arg0, _arg1); // 得出方法返回值之后写写入序列化数据 reply.writeNoException(); reply.writeInt(_result); return true ; } } return super .onTransact(code, data, reply, flags); } static final int TRANSACTION_addition = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0 ); } |