一.什么是AIDL
AIDL(Android Interface Definition Language)是一种接口定义语言,可实现进程间通信
二.AIDL的使用
1.创建aidl文件
需要在aidl文件中写一个接口,接口里面写你想要回调的方法
例如
package com.ojr.aidl;
import com.ojr.aidl.Person;
interface IPerson{
String say(String someone);
String greet(in Person person);
}
需要注意:
aidl文件接口里面的方法不可用,public,private的关键字修饰
可以引用其它aidl文件中定义的接口,但是不能够引用java类文件中定义的接口
AIDL服务默认支持类型: Java的原生类型,String和CharSequence, List 和 Map ,List和Map 对象的元素必须是AIDL支持的数据类型(其他类型需要import,如例子中的Person)
非原始类型中,除了String和CharSequence以外,其余均需要一个方向指示符。方向指示符包括in、out、和inout。in表示由客户端设置,out表示由服务端设置,inout表示客户端和服务端都设置了该值。
2.创建服务端
IPerson接口中的抽象内部类Stub继承android.os.Binder类并实现IPerson接口,比较重要的方法是asInterface(IBinder)方法,该方法会将IBinder类型的对象转换成IPerson类型,必要的时候生成一个代理对象返回结果。该文件通过aidl文件在gen目录下自动生成然后,在aidlservice的onbind方法中返回stub
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return stub;
}
IPerson.Stub stub = new IPerson.Stub() {
@Override
public String say(String someone) throws RemoteException {
// TODO Auto-generated method stub
Log.d(TAG, " say: " + someone);
return "Hello " + someone;
}
@Override
public String greet(Person person) throws RemoteException {
String greeting = "hello, " + person.getName();
switch (person.getSex()) {
case 0:
greeting = greeting + ", you're handsome.";
break;
case 1:
greeting = greeting + ", you're beautiful.";
break;
}
return greeting;
}
};
3.创建客户端
需要把服务端的aidl文件copy到客户端中,编译器同样会生成相对应的IPerson.java文件
在客户端中,需要重写ServiceConnection中的onServiceConnected方法将IBinder类型的对像转换成IPerson类型
绑定aidlservice之后就可以进行进程间的通信了
private IPerson person;
private ServiceConnection conn = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("ServiceConnection", "onServiceConnected() called");
person = IPerson.Stub.asInterface(service);
Log.d(TAG, "BIND+++success");
}
@Override
public void onServiceDisconnected(ComponentName name) {
//This is called when the connection with the service has been unexpectedly disconnected,
//that is, its process crashed. Because it is running in our same process, we should never see this happen.
Log.i("ServiceConnection", "onServiceDisconnected() called");
}
};
三.AIDL传递复杂对象
传递的对象类需要实现Parcelable接口
必须提供一个名为CREATOR的static final属性 该属性需要实现android.os.Parcelable.Creator接口
读取变量与写入变量的顺序需一致,不然会出错