通过binder建立进程间通信,主要分为两步:
1. 定义一个binder的服务(在androidManifest.xml中声明)接受远端请求。
服务中创建一个binder实例, 在接收到客户端的连接时,向请求方返回回binder的引用。重写Binder的onTransact方法,处理来自远端的调用消息。
public class MyService extends Service {private static final String TAG = "MyService";@Overridepublic IBinder onBind(Intent intent) {OLog.i(TAG, "onBind");return myBinder;}Binder myBinder = new Binder() {@Overrideprotected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {switch (code) {case RemoteProtocal.CODE_ADD: {int a = data.readInt();int b = data.readInt();int result = add(a, b);reply.writeInt(result);return true;}}return super.onTransact(code, data, reply, flags);}};public int add(int a, int b) {return a + b;}
}
2. 调用bindService方法,根据Binder服务名称建立与服务的连接。
连接成功后, 可以获得远程服务中binder的引用。通过该引用即可调用其binder.transact方法与远端进行通信。 transact有三个个关键参数,分别是消息的命令码、入参及返回值的引用。
private void bindRemoteService() {// 远程服务具体名称ComponentName componentName = new ComponentName(this, "com.me.obo.mybinder.server.MyService");Intent intent = new Intent();intent.setComponent(componentName);// 绑定到服务bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);}ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName componentName, IBinder iBinder) {///绑定成功后, 获取binder的引用mBinder = iBinder;tvConnectState.setText("Connected");}@Overridepublic void onServiceDisconnected(ComponentName componentName) {}};private int add(int a, int b) {Parcel data = Parcel.obtain();Parcel reply = Parcel.obtain();// 写入参数 adata.writeInt(a);// 写入参数 bdata.writeInt(b);try {//通过mbinder代理 调用远程服务mBinder.transact(RemoteProtocal.CODE_ADD, data, reply, 0);// 获取远程计算结果int result = reply.readInt();OLog.i(TAG, "result = " + result);return result;} catch (RemoteException e) {e.printStackTrace();}return 0;}