Android IPC浅析之Binder

作者: blink_dagger | 来源:发表于2016-09-05 07:28 被阅读244次

    在认识IPC(Inter-Process Communication,进程间通信)之前,肯定要先理解什么是线程,什么是进程?在多数操作系统中,线程是最小的可操作调度单元。而进程一般则是一个具体的应用(比如QQ、微信),其可以包含有多个线程。要在不同的进程进行数据的传输与通信,就需要用到IPC机制了。

    在Android中跨进程通信的方式有很多,如intent传递、读写文件、socket通信、SharedPreferences(不可靠)、ContentProvider以及Binder等。本文主要讲解Binder机制的用法及其简单原理,这次的demo是客户端跨进程请求服务端返回一个我们需要的int值,效果如下:


    简单来说Binder是Android系统为我们提供的一个用于进程通信的类,我们一般通过AIDL语言自动让ide工具为我们生成(如果你不嫌累不嫌头疼完全可以自己写),其结构类似这样:

    package com.example.lucky.aidl;
    // Declare any non-default types here with import statements
    
    public interface IMyAidlInterface extends android.os.IInterface
    {
        public int plusResult(int a, int b) throws android.os.RemoteException;
        /** Local-side IPC implementation stub class. */
        public static abstract class Stub extends android.os.Binder implements com.example.lucky.aidl.IMyAidlInterface
        {
            private static final java.lang.String DESCRIPTOR = "com.example.lucky.aidl.IMyAidlInterface";
            /** Construct the stub at attach it to the interface. */
            public Stub()
            {
                this.attachInterface(this, DESCRIPTOR);
            }
            /**
             * Cast an IBinder object into an com.example.lucky.aidl.IMyAidlInterface interface,
             * generating a proxy if needed.
             */
            public static com.example.lucky.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.example.lucky.aidl.IMyAidlInterface))) {
                return ((com.example.lucky.aidl.IMyAidlInterface)iin);
            }
                return new com.example.lucky.aidl.IMyAidlInterface.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
            {
                return super.onTransact(code, data, reply, flags);
            }
            private static class Proxy implements com.example.lucky.aidl.IMyAidlInterface
            {
            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 int plusResult(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_plusResult, _data, _reply, 0);
            _reply.readException();
            _result = _reply.readInt();
            }
            finally {
            _reply.recycle();
            _data.recycle();
            }
            return _result;
            }
            }
            static final int TRANSACTION_plusResult = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        }
    
    }
    
    

    乍一看代码很杂乱,逻辑也很复杂,其实对于我们这样的萌新只需要理解清这个接口的内部类Stub、内部类中的asInterface(android.os.IBinder obj)onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)、以及Proxy就可以简单使用Binder了。下面我会逐一分析这些。

    Stub

    这个Stub就是我们需要的Binder类了,当我们在客户端bindService时会通过远程服务端的onBinder方法中会return 给我们.

        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            return mBinder;
        }
    

    通过这个Binder类,我们可以就在客户端取得 他的内部类Proxy,从而在客户端完成相应操作。

    asInterface(android.os.IBinder obj)

    通过此方法我们可以将服务端生成的Binder对象(Stub)转化成AIDL接口型的对象。需要注意的是此方法是区分进程的,如果客户端和服务端处于同一进程,则不会进行转换,直接把Stub返回给客户端,当处于不同进程时,会返回Stub.Proxy对象。

    public static com.example.lucky.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.example.lucky.aidl.IMyAidlInterface))) {
                return ((com.example.lucky.aidl.IMyAidlInterface)iin);
            }
                return new com.example.lucky.aidl.IMyAidlInterface.Stub.Proxy(obj);
    }
    
    onTransact

    此方法运行在服务端的Binder线程池中,当我们在客户端远程请求服务端的方法时,就会执行该方法。我们可以发现它就收的参数类型int code, android.os.Parcel data, android.os.Parcel reply, int flags都是可序列化的Parcel 型,这点后面会讲。基本原理就是服务端通过data取出客户端传入的参数,然后写入reply返回给客户端。

    Proxy

    Proxy可以直译为代理人,从名字上我们就能看出这是服务端返回给我们的Binder的一个代理人(为了与时俱进,我们可以把它称作经纪人~),通过它我们可以在客户端远程调用服务端的方法。注意此时会挂起客户端的当前线程,直到服务器返回数据成功,所以如果我们直接在此处更新UI是很容易引起ANR让我们的应用挂掉(因为等待服务器一般都比较耗时)!为了避免ANR,常用的方法就是新建线程通过判断返回的Proxy是否为null来请求服务端。

    通过上面的分析我们应该对Binder的工作流程有了一定的了解,接下来就通过demo代码,更直观地学会如何使用Binder进行进程间通信。

    Demo创建流程

    • 1 创建AIDL接口
    // IMyAidlInterface.aidl
    package com.example.lucky.aidl;
    
    // Declare any non-default types here with import statements
    
    interface IMyAidlInterface {
    
        int plusResult(in int a, in int b);
    }
    
    

    这儿只声明了一个方法plusResult,往后看就会发现,通过AIDL暴露出来的方法会在Service端实现,从而让客户端调用。这儿我们只关心AIDL文件中支持的数据类型:java基本数据类型、ArrayList(里面元素也必须支持AIDL)、HashMap(里面元素也必须支持AIDL)、所有可序列化的自定义对象(实现了Parcelable接口)。这儿我们的plusResult方法中接收的参数是最简单的int型,如果是自定义的Parcel对象,我们还需要额外创建AIDL文件声明该对象。例:

     int plusResult(in int a, in User use);
    

    我们必须在同目录下声明该User对象:

    // IMyAidlInterface.aidl
    package com.example.lucky.aidl;
    
    parcelable User;
    

    参数名前面的in、out分别表示输入、输出型参数。

    • 2 创建远程服务端
      此例的Service为了额外创建新的工程直接通过android:process=".anotherProcess"属性将其进程定义为了其他线程。
    public class PlusService extends Service {
    
        private Binder mBinder;
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            return mBinder;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            mBinder = new IMyAidlInterface.Stub() {
                @Override
                public int plusResult(int a, int b) throws RemoteException {
                    /*try {
                        new Thread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }*/
                    return a+b;
                }
            };
        }
    }
    

    代码十分简单,主要在onCreate时实例化 了IMyAidlInterface.Stub,在其中实现了客户端请求的plusResult方法,然后通过onBind传递出去。

    • 3 客户端bindService进行远程请求
    public class MainActivity extends AppCompatActivity {
    
        private ServiceConnection mServiceConnection;
        private int plusResult;
        @InjectView(R.id.firstEditText)
        EditText firstEditText;
        @InjectView(R.id.secondEditText)
        EditText secondEditText;
        @InjectView(R.id.result)
        TextView result;
        @InjectView(R.id.mButton)
        Button mButton;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ButterKnife.inject(this);
            mButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if ((firstEditText.getText().length()==0) || (secondEditText.getText().length()==0)) {
                        Toast.makeText(MainActivity.this,"请输入数字",Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        final int a = Integer.valueOf(firstEditText.getText().toString().trim());
                        final int b = Integer.valueOf(secondEditText.getText().toString().trim());
                        mServiceConnection = new ServiceConnection() {
    
                            //onServiceConnected onServiceDisconnected都是在UI线程中进行的,所以当需要耗时操作时,可以通过判断bookManager(proxy)对象是否为空,在子线程中进行
                            @Override
                            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                                IMyAidlInterface myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
                                try {
                                    plusResult = myAidlInterface.plusResult(a,b);
                                    result.setText(" "+plusResult);
                                    Toast.makeText(MainActivity.this,"服务器响应拉,亲~",Toast.LENGTH_LONG).show();
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                            }
    
                            @Override
                            public void onServiceDisconnected(ComponentName componentName) {
    
                            }
                        };
                        Intent intent = new Intent(MainActivity.this,PlusService.class);
                        if (mServiceConnection != null) {
                            bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
                        }
                    }
    
                }
            });
        }
    
        @Override
        protected void onDestroy() {
            if (mServiceConnection != null) {
                unbindService(mServiceConnection);
            }
            super.onDestroy();
        }
    }
    

    在ServiceConnection 的onServiceConnected回调方法中我们获得了我们想要的经纪人IMyAidlInterface myAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);,通过它就可以远程请求服务端的方法了,这儿为了代码简洁没有新建线程处理,其实只要在服务端sleep一下,客户的程序就很容易ANR挂掉了,有兴趣的同学可以自己尝试一下。最后千万别忘记在客户端unbindService,这样一个简单的跨进程通信demo就创建好了~

    总结下使用AIDL时的那些坑:
    • 客户端、服务端所有AIDL文件的packagename必须手动修改为相同的
    • 远程服务端需要通过android:exported="true"属性暴露出来
    • 有时候找不到系统自动生成的Binder类,我们需要remake一下这个工程
    • 自定义创建的对象一定要实现Parcelable且额外声明
    • AIDL即使在相同package内,也要手动导包
      。。。。。。

    相关文章

      网友评论

        本文标题:Android IPC浅析之Binder

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