AIDL(Android Interface Definition Language)
进程间的通信
1.创建一个.aidl文件,Eclipse自动编译,AndroidStudio手动去编译
package com.pt.aidl;
interface IMyAIDLTest{
int add(int num1,int num2);
}
2.创建一个Service,记得在AndroidManifest中声明且添加
android:exported="true"
android:process=":remote"
android:name=".IRemoteService"
android:label="@string/app_name"
属性。
public class IRemoteService extends Service {
/**
* 当客户端绑定到该服务会调用
*/
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
private IBinder iBinder = new IMyAIDLTest.Stub() {
@Override
public int add(int num1, int num2) throws RemoteException {
Log.d("TAG","收到远程客户数据,参数是:num1 = " + num1 + ",num2 = " + num2);
return num1 + num2;
}
};
}
3.创建一个客户端程序
简单的加法:
复制服务端的.aidl文件
然后在客户端启动时绑定服务
private void bindService() {
//获取服务端
Intent intent = new Intent();
//新版本5.0 必须显示启动,绑定服务
intent.setComponent(new ComponentName("com.pt.aidltest", "com.pt.aidltest.IRemoteService"));
//绑定了自动生成
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
4.conn作为成员变量
实现它的方法将service转为IMyAIDLTest接口
//拿到远程的服务iMyAIDLTest为成员变量,service为服务端返回的IBinder
iMyAIDLTest = IMyAIDLTest.Stub.asInterface(service);
5.调用iMyAIDLTest远程服务的方法,记得在OnDestroy()中释放资源unBindService(conn)
除了short类型。
in List<String> aList; //标记in,out,inout
List 是个接口,客户端接收转为实例ArrayList
自定义类型
1.Person implement Parcelable
//读入和写入的顺序相同
public Person(Parcel source){
this.name = source.readString(),
this.age = source.readInt();
}
2.创建一个Person.aidl文件,声明Person类
package com.pt.aidl;
parcelable Person;
3.在要应用的.aidl文件中
package com.pt.aidl;
import com.pt.aidl.Person;
interface IMyAIDL{
List<Person> add(in Person person);
}
原理: