什么是AIDL呢?其实就是 Android Interface definition language,翻译为安卓接口定义语言,主要用于进程间的通信。该如何使用呢?
在ansroid stdio中,首先在第一个App中先定义一个远程服务,并提供可调用的方法。然后新建一个aidl文件RemoteService.aidl(在main文件夹下右键新建aidl文件,然后rebuild一下工程),将服务中暴露的方法写入到接口中,此时系统自动生成RemoteService.Stub类(该类位于app\build\generated\source\aidl\debug\),此类作为第三方类,在服务中继承这个类,在onBind()方法中返回给调用对象即可。代码如下:
在第二个App中,如果要调用第一个App的服务中的方法,只需要将 RemoteService.aidl文件拷贝一份到aidi文件夹下,然后rebuild一下工程,工程将自动生成RemoteService.Stub类,此时我们只需要绑定服务获得第三方对象即可。代码如下:
public class RemoteService extends Service {
//把我们定义的中间人对象返回
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
//定义一个方法
public void methodService(){
System.out.println("我是远程服务里面的方法");
}
//[1]定义一个中间人对象(IBinder)
private class MyBinder extends Stub{
@Override
public void callMethodService() {
//调用方法
methodService();
}
}
}
aidl文件如下:
interface Iservice {
//把想暴露的方法定义在接口里面
void callMethodService();
}
在第二个App中,如果要调用第一个App的服务中的方法,只需要将 RemoteService.aidl文件拷贝一份到aidi文件夹下,然后rebuild一下工程,工程将自动生成RemoteService.Stub类,此时我们只需要绑定服务获得第三方对象即可。代码如下:
Intent intent = new Intent();
//查找服务,使用隐式意图
intent.setAction("com.xj.remoteService");
//[2]调用bindservice 目的为了获取我们定义的中间人对象 就可以间接的调用服务里面的方法了
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
//监听服务的状态
private class MyConn implements ServiceConnection{
//当服务连接成功
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//获取我们定义的中间人对象
rService = (RemoteService.Stub) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
希望能对大家有所帮助。