Android AIDL使用 & 工作原理

首先回顾下AIDL的使用。
1.新建aidl文件,MyAidlServer.aidl .

interface MyAidlServer {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

    int addTwoNums(int a,int b);
}

同步下工程,就会生成对应aidl文件的接口类。

public interface MyAidlServer extends android.os.IInterface {
    /**
     * Local-side IPC implementation stub class.
     */
    public static abstract class Stub extends android.os.Binder implements com.example.dengxuan.learnproject.MyAidlServer {
        private static final java.lang.String DESCRIPTOR = "com.example.dengxuan.learnproject.MyAidlServer";

        /**
         * Construct the stub at attach it to the interface.
         */
        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        /**
         * Cast an IBinder object into an com.example.dengxuan.learnproject.MyAidlServer interface,
         * generating a proxy if needed.
         */
        public static com.example.dengxuan.learnproject.MyAidlServer asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.example.dengxuan.learnproject.MyAidlServer))) {
                return ((com.example.dengxuan.learnproject.MyAidlServer) iin);
            }
            return new com.example.dengxuan.learnproject.MyAidlServer.Stub.Proxy(obj);
        }

        @Override
        public android.os.IBinder asBinder() {
            return this;
        }

        @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: {
                    reply.writeString(DESCRIPTOR);
                    return true;
                }
                case TRANSACTION_basicTypes: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    long _arg1;
                    _arg1 = data.readLong();
                    boolean _arg2;
                    _arg2 = (0 != data.readInt());
                    float _arg3;
                    _arg3 = data.readFloat();
                    double _arg4;
                    _arg4 = data.readDouble();
                    java.lang.String _arg5;
                    _arg5 = data.readString();
                    this.basicTypes(_arg0, _arg1, _arg2, _arg3, _arg4, _arg5);
                    reply.writeNoException();
                    return true;
                }
                case TRANSACTION_addTwoNums: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    int _arg1;
                    _arg1 = data.readInt();
                    int _result = this.addTwoNums(_arg0, _arg1);
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.example.dengxuan.learnproject.MyAidlServer {
            private android.os.IBinder mRemote;

            Proxy(android.os.IBinder remote) {
                mRemote = remote;
            }

            @Override
            public android.os.IBinder asBinder() {
                return mRemote;
            }

            public java.lang.String getInterfaceDescriptor() {
                return DESCRIPTOR;
            }

            /**
             * Demonstrates some basic types that you can use as parameters
             * and return values in AIDL.
             */
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeInt(anInt);
                    _data.writeLong(aLong);
                    _data.writeInt(((aBoolean) ? (1) : (0)));
                    _data.writeFloat(aFloat);
                    _data.writeDouble(aDouble);
                    _data.writeString(aString);
                    mRemote.transact(Stub.TRANSACTION_basicTypes, _data, _reply, 0);
                    _reply.readException();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }

            @Override
            public int addTwoNums(int a, int b) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                int _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeInt(a);
                    _data.writeInt(b);
                    mRemote.transact(Stub.TRANSACTION_addTwoNums, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readInt();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

        static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_addTwoNums = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    }

    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException;

    public int addTwoNums(int a, int b) throws android.os.RemoteException;
}

2.新建service类,MyAidlService

public class MyAidlService extends Service {

    MyAidlServer.Stub myBinder = new MyAidlServer.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public int addTwoNums(int a, int b) throws RemoteException {
            return a+b;
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("dx","onBind");
        return myBinder;
    }
}

3.绑定Service。

    private void bindMsgService(){
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, MyAidlService.class);
        bindService(intent,mConn,Context.BIND_AUTO_CREATE);
    }

   MyAidlServer server;
   private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            server = MyAidlServer.Stub.asInterface(service);
            if(server != null){
                try {
                    int i = server.addTwoNums(5, 6);
                    Log.i("dx result",String.valueOf(i));
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("dx add","onServiceDisconnected");
            server = null;
        }
    };

至此,一个简单的AIDL使用的例子就完成了。 下面我们根据这个例子来分析AIDL的工作原理。

客户端通过bindService来绑定服务端的服务。当服务绑定成功后,ServiceConnection 中 有一个onServiceConnected的回调,第一个参数ComponentName对应服务组件(包含Service的包名和类的全名)
第二个参数返回一个iBinder对象。通过 MyAidlServer.Stub.asInterface 实例化出具体的对象。再来看asInterface的代码


image.png

如果在同进程中(即MainActivity 与 MyAidlService在同一进程),代码将会走到

return ((com.example.dengxuan.learnproject.MyAidlServer) iin); 

中,这里返回来的实际上是之前我们在MyAidlService 的 onBind方法中返回的对象。 也就是 MyAidlServer.Stub 对象。


如果是跨进程调用,service定义


image.png

在另一个app中使用如下方式调用当前app的service:

        Intent intent = new Intent();
        intent.setAction("com.dx.aidl");
        intent.setPackage("com.example.dengxuan.learnproject");
        bindService(intent,mConn, Context.BIND_AUTO_CREATE);

或者在定义service的时候 指定了 属性android:process=":remote"

那么asInterface中将会走到

 return new com.example.dengxuan.learnproject.MyAidlServer.Stub.Proxy(obj);

此时返回回来的是 一个代理对象。


image.png

然后在通过代理对象去调用不同进程的方法 涉及到进程间的数据传输, android系统中的binder进程间通信(IPC)就使用了Parcel类来进行客户端与服务端数据的交互。在代理类里的方法实现首先把需要传输的数据包装成Parcel对象。


image.png

然后通过调用 transact 方法 指定调用的方法名(Stub.TRANSACTION_addTwoNums),以及参数(_data),以及方法的返回结果(_reply) 这是一个同步方法,执行完成后的结果保存在_reply 对象中。代理对象调用transact会映射到远端服务的onTransact方法中,在这里具体完成调用过程。


image.png

你可能感兴趣的:(Android AIDL使用 & 工作原理)