最近一直在研究AIDL,AIDL是为不同进程之间通讯而设计的,它使用了Binder的机制,我这里不打算讲解Binder的原理,因为我也不太清楚。其基本思想就是你的进程(可以称之为本地端)想调用另外一个进程(可称之为服务端)提供的功能,比如Add。这个时候我们必须创建一个AIDL文件,假如文件名为IAddService.aidl,内容大致如下:
interface IAddService {int Add(int a, int b)
}
编译完成后系统会为这个aidl文件自动生成IAddService.java,然后在服务端要创建一个IAddService.Stub的Binder实例并实现Add方法,
代码大致如下:
IAddService.Stub mBinder = new IAddService.Stub() {
@Override
public int Add(int a, int b) throws RemoteException {
// TODO Auto-generated method stub
return a + b;
}
};
接下来如果本地端能够拿到这个mBinder实例,就可以调用服务端提供的功能了,代码大致如下:
IAddService mService;
mService = IAddService.Stub.asInterface(mBinder);
int result = mService.Add(9, 10);
那么本地怎么才能拿到服务端创建的那个mBinder实例呢?
一般做法就是在服务端创建一个继承于Service的类,在该类中去创建之前说的那个mBinder实例,在onBind方法里返回这个mBinder。
代码大致如下:
public class mAIDLService extends Service {
private final IAddService.Stub mBinder = new IAddService.Stub() {
@Overridepublic int Add(int a, int b) throws RemoteException {
// TODO Auto-generated method stub
return a + b;
}
};
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
@Overridepublic void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//return super.onStartCommand(intent, flags, startId);
}
}
本地端要做的就是去绑定上面说的那个mAIDLService,绑定成功后我们就可以拿到mBinder了,代码大致如下:
IAddService mService;
private ServiceConnection mConnection = new ServiceConnection() {
@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
//这里就拿到了服务端的那个mBinder
mService = IAddService.Stub.asInterface(service);
int result = mService.Add(9, 10);
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.d("wujiang","disconnect service");
mService = null;
}
};
THE END