AIDL解析

2019-08-06  本文已影响0人  sanfen

实现

  1. 创建aidl文件

在build之后会在build目录生成IMyAidlInterface的实现类

interface IMyAidlInterface {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    int add(int aInt, int bInt);
    int min(int aInt, int bInt);
}

  1. 创建Service,并实现IMyAidlInterface.Stub()接口
    IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {
        @Override
        public int add(int aInt, int bInt) {
            return aInt + bInt;
        }

        @Override
        public int min(int aInt, int bInt) {
            return aInt < bInt ? aInt : bInt;
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }
  1. 在Activity中bindService
  bindService(intent, conn, Context.BIND_AUTO_CREATE);
private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            iMyAidlInterface = null;
        }
    };

解析

服务端

transact [træn'zækt]

        @Override
        public boolean onTransact(int code, 
        android.os.Parcel data, 
        android.os.Parcel reply,
        int flags) throws android.os.RemoteException {
            ...
        }

可以看到onTransact有四个参数 code,data,replay,flags

data.enforceInterface(DESCRIPTOR);
与客户端的writeInterfaceToken对用,标识远程服务的名称

客户端

实际上调用了Proxy

       public static com.sanfen.aidl.IMyAidlInterface asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.sanfen.aidl.IMyAidlInterface))) {
                return ((com.sanfen.aidl.IMyAidlInterface) iin);
            }
            return new com.sanfen.aidl.IMyAidlInterface.Stub.Proxy(obj);
        }

最后通过transact方法传递给服务端的onTransact(),并在_reply中返回值

    mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
    ==>
    onTransact(int code, android.os.Parcel data, android.os.Parcel reply,int flags)

源码

上一篇下一篇

猜你喜欢

热点阅读