
1.AIDL定义
AIDL是android interface definition language的缩写,它对android IPC组件Binder进行了封装。使用它不需理会底层IPC的实现,只需要简单的定义接口,然后ADT编译生成IPC需要的java文件。极大的方便了开发者和提升了开发的速度及规范。
2.AIDL的使用
AIDL使用很简单,只需要三个步骤:
1)接口的定义
在aidl文件中定义需要给远程调用的接口,它会被ADT自动编译成java文件
2)接口的实现
接口定义好了,需要实现接口
/**
* A secondary interface to the service.
*/
private final ISecondary.Stub mSecondaryBinder = new ISecondary.Stub() {
public int getPid() {
return Process.myPid();
}
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
}
};
实现好接口后,还需要定义Service,实现它的 onBind 方法,然后在onBind方法中将实现的 binder 对象返回,供远程客户端调用。
3)接口的调用
首先在客户端绑定远程服务:
bindService(new Intent(ISecondary.class.getName()),
mSecondaryConnection, Context.BIND_AUTO_CREATE);
然后实现ServiceConnecton接口,在绑定成功后将远端Service的binder 对象返回:
/**
* Class for interacting with the secondary interface of the service.
*/
private ServiceConnection mSecondaryConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
// Connecting to a secondary interface is the same as any
// other interface.
mSecondaryService = ISecondary.Stub.asInterface(service);
mKillButton.setEnabled(true);
} public void onServiceDisconnected(ComponentName className) {
mSecondaryService = null;
mKillButton.setEnabled(false);
}
};
最后直接调用之前定义好的接口即可