美文网首页
AIDL的简单使用以及Binder机制源码解析

AIDL的简单使用以及Binder机制源码解析

作者: zzl93 | 来源:发表于2018-05-22 11:08 被阅读81次

    本篇是在https://www.jianshu.com/p/4ee3fd07da14基础上写的。方便自己日后回忆。
    一、aidl的简单使用
    aidl的使用很简单,其实就是创建一个aidl文件,

    interface IRemoteInterface {
    void test();
    int add(int a,int b);
        /**
         * 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);
    }
    

    会自动生成一个继承Binder的实现aidl接口的Stub类,这个然后在service(进程1)中onBind方法中返回这个binder(如下代码)

    
    public class RemoteService extends Service {
        // 实例化AIDL的Stub类(Binder的子类)
        IRemoteInterface.Stub mBinder = new IRemoteInterface.Stub(){
    
            @Override
            public void test() throws RemoteException {
                System.out.println("客户端通过AIDL与远程后台成功通信");
            }
    
            @Override
            public int add(int a, int b) throws RemoteException {
                return a+b;
            }
    
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
            }
        };
    
        //重写与Service生命周期的相关方法
        @Override
        public void onCreate() {
            super.onCreate();
    
            System.out.println("执行了onCreat()");
    
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            System.out.println("执行了onStartCommand()");
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            System.out.println("执行了onDestory()");
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
    
            System.out.println("执行了onBind()");
            //在onBind()返回继承自Binder的Stub类型的Binder,非常重要
            return mBinder;
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            System.out.println("执行了onUnbind()");
            return super.onUnbind(intent);
        }
    
    
    }
    

    然后在client(进程2)中拿到server传过来的binder(代理),即可通过这个server中的binder代理来调用aidl中写好的方法。从而实现IPC。

    public class MainActivity extends AppCompatActivity {
     Button btn,btn2;
     private IRemoteInterface iRemoteInterface;
        //创建ServiceConnection的匿名类
        private ServiceConnection connection=new ServiceConnection() {
            //重写onServiceConnected()方法和onServiceDisconnected()方法
            //在Activity与Service建立关联和解除关联的时候调用
    
            //在Activity与Service建立关联时调用
            @Override
         public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                //IRemoteInterface.Stub.asInterface()方法获取服务器端返回的IBinder对象
                //将IBinder对象传换成了IRemoteInterface接口对象
                iRemoteInterface=IRemoteInterface.Stub.asInterface(iBinder);
                try {
                    iRemoteInterface.test();
                    int result=iRemoteInterface.add(1,2);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
    
         @Override
         public void onServiceDisconnected(ComponentName componentName) {
    
         }
     };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btn=findViewById(R.id.btn);
            btn2=findViewById(R.id.btn2);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
    //通过Intent指定服务端的服务名称和所在包,与远程Service进行绑定
                    //参数与服务器端的action要一致,即"服务器包名.aidl接口文件名"
                    Intent intent = new Intent("com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface");
    
                    //Android5.0后无法只通过隐式Intent绑定远程Service
                    //需要通过setPackage()方法指定包名
                    intent.setPackage("com.example.zhaoziliang.rxjavaandretrofitdemo");
    
                    //绑定服务,传入intent和ServiceConnection对象
                    bindService(intent, connection, Context.BIND_AUTO_CREATE);
    
                }
            });
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        iRemoteInterface.test();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    二、分析binder的源码
    源码不多,先列出来,下面挨个方法写出了自己的理解

    package com.example.zhaoziliang.rxjavaandretrofitdemo;
    // Declare any non-default types here with import statements
    
    public interface IRemoteInterface extends android.os.IInterface
    {
    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder implements com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface
    {
    private static final java.lang.String DESCRIPTOR = "com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface";
    /** Construct the stub at attach it to the interface. */
    public Stub()
    {
    this.attachInterface(this, DESCRIPTOR);
    }
    /**
     * Cast an IBinder object into an com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface interface,
     * generating a proxy if needed.
     */
    public static com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface asInterface(android.os.IBinder obj)
    {
    if ((obj==null)) {
    return null;
    }
    android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
    if (((iin!=null)&&(iin instanceof com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface))) {
    return ((com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface)iin);
    }
    return new com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface.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_test:
    {
    data.enforceInterface(DESCRIPTOR);
    this.test();
    reply.writeNoException();
    return true;
    }
    case TRANSACTION_add:
    {
    data.enforceInterface(DESCRIPTOR);
    int _arg0;
    _arg0 = data.readInt();
    int _arg1;
    _arg1 = data.readInt();
    int _result = this.add(_arg0, _arg1);
    reply.writeNoException();
    reply.writeInt(_result);
    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;
    }
    }
    return super.onTransact(code, data, reply, flags);
    }
    private static class Proxy implements com.example.zhaoziliang.rxjavaandretrofitdemo.IRemoteInterface
    {
    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;
    }
    @Override public void test() throws android.os.RemoteException
    {
    android.os.Parcel _data = android.os.Parcel.obtain();
    android.os.Parcel _reply = android.os.Parcel.obtain();
    try {
    _data.writeInterfaceToken(DESCRIPTOR);
    mRemote.transact(Stub.TRANSACTION_test, _data, _reply, 0);
    _reply.readException();
    }
    finally {
    _reply.recycle();
    _data.recycle();
    }
    }
    @Override public int add(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_add, _data, _reply, 0);
    _reply.readException();
    _result = _reply.readInt();
    }
    finally {
    _reply.recycle();
    _data.recycle();
    }
    return _result;
    }
    /**
         * 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();
    }
    }
    }
    static final int TRANSACTION_test = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    static final int TRANSACTION_basicTypes = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2);
    }
    public void test() throws android.os.RemoteException;
    public int add(int a, int b) throws android.os.RemoteException;
    /**
         * 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;
    }
    

    1、attachInterface(value,key)
    这个方法写在Stub()构造方法中,其实就是将本身的binder作为value,将DESCRIPTOR字符串作为key存起来了。
    void attachInterface(IInterface plus, String descriptor);
    // 作用:
    // 1. 将(descriptor,plus)作为(key,value)对存入到Binder对象中的一个Map<String,IInterface>对象中
    // 2. 之后,Binder对象 可根据descriptor通过queryLocalIInterface()获得对应IInterface对象(即plus)的引用,可依靠该引用完成对请求方法的调用
    2、queryLocalInterface(String descriptor)
    IInterface queryLocalInterface(String descriptor) ;
    // 作用:根据 参数 descriptor 查找相应的IInterface对象(即plus引用)
    3、asInterface
    在client中IRemoteInterface.Stub.asInterface(binder)方法传入服务器端返回的IBinder对象,将IBinder对象传换成了IRemoteInterface接口对象
    在server中返回的是biinder本身,在client中返回的是binder的代理对象
    4、onTransact
    进程2的client调用进程1的server的方法的时候,实际是在此方法中调用的
    boolean onTransact(int code, Parcel data, Parcel reply, int flags);
    // 定义:继承自IBinder接口的
    // 作用:执行Client进程所请求的目标方法(子类需要复写)
    // 参数说明:
    // code:Client进程请求方法标识符。即Server进程根据该标识确定所请求的目标方法
    // data:目标方法的参数。(Client进程传进来的,此处就是整数a和b)
    // reply:目标方法执行后的结果(返回给Client进程)
    // 注:运行在Server进程的Binder线程池中;当Client进程发起远程请求时,远程请求会要求系统底层执行回调该方法
    4、BinderProxy
    final class BinderProxy implements IBinder {
    // 即Server进程创建的Binder对象的代理对象类
    // 该类属于Binder的内部类
    }

    image.png

    相关文章

      网友评论

          本文标题:AIDL的简单使用以及Binder机制源码解析

          本文链接:https://www.haomeiwen.com/subject/ahhhjftx.html