原理简介
我们都知道android 是通过IBinder来实现IPC(Inter Process Communication)进程间通信的。。。
借用一下:
1. Client、Server和Service Manager实现在用户空间中,Binder驱动程序实现在内核空间中
2. Binder驱动程序和Service Manager在Android平台中已经实现,开发者只需要在用户空间实现自己的Client和Server
3. Binder驱动程序提供设备文件/dev/binder与用户空间交互,Client、Server和Service Manager通过open和ioctl文件操作函数与Binder驱动程序进行通信
4.
Client和Server之间的进程间通信通过Binder驱动程序间接实现
5. Service Manager是一个守护进程,用来管理Server,并向Client提供查询Server接口的能力
AIDL的使用
aidl是 Android Interface definition language的缩写,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口
ITestService.aidl文件
package test.aidl;
interface ITestService {
void start();
}注意在client端和server端中的aidl文件的的包名必须是一样的,此处必须是test.aidl
自动生成ITestService类,其中有Stub子类
public static test.aidl.ITestService asInterface(android.os.IBinder obj) {
......
}Stub的asInterface方法返回了ITestService对象
lbb.demo.first进程中的服务,充当Server角色
package lbb.demo.first;
public class RemoteService extends Service {
private TestService mITestService;
public class TestService extends ITestService.Stub {
public void start() {
Log.d("LiaBin", "RemoteService start");
}
}
@Override
public void onCreate() {
super.onCreate();
//实例化Binder
mITestService = new TestService();
}