Android AIDL的简单使用
AIDL,是Android中IPC通信的一种,有其独特的优势,能处理大量的并发请求,能满足多进程同时调用服务端的需求。既然这么强大,我们不妨一探究竟,该如何使用呢?
1、首先,我们需要编写一个AIDL的文件,直接在Android Studio项目上右键,新建一个名为IMyAidlInterface的AIDL文件,此时在工程目录中会生成一个和java同级的aidl包
接着,我们在IMyAidlInterface.aidl中定义两个方法,如下:
// IMyAidlInterface.aidl
package
com.demo.psp.aidldemo;
// Declare any non-default types here with import statements
interface
IMyAidlInterface {
voidaddLog(Stringadd);
StringgetLog(Stringget);
}
此时我们build一下工程,发下build目录下多了一个java文件,说明我们aidl文件的书写是没问题的,如下图所示:
定义好aidl接口以后,我们需要写一个远程服务端实现它。此时定义一个服务:
public classAIDLServiceextendsService
{
publicAIDLService()
{
}
privateIMyAidlInterface.StubaidlDemo=newIMyAidlInterface.Stub(){
@Override
public voidaddLog(String
add)throws RemoteException {
Log.d("pspadd=====",add);
}
@Override
publicStringgetLog(String
get)throwsRemoteException {
Log.d("pspget=====",get);
return
get;
}
};
//aidl的接口数据在binder里面返回
@Override
publicIBinderonBind(Intent
intent) {
returnaidlDemo;
}
在这个服务中,我们实例化IMyAidlInterface.Stub(它其实是一个Binder对象),实现我们的在AIDL接口中定义的方法,并在onBind中返回。
由于要实在跨进程通信,我们可以把我们的service运行在一个独立的进程中,这样就构成了进程间通信的场景。我们在功能清单文件中做如下修改:
<service
android:name=".service.AIDLService"
android:process=":remote">
</service>
2、客户端的实现:
首先需要绑定远程服务,将服务端返回的Binder对象转换成AIDL接口,然后就可以调用服务端的方法了,代码如下:
public class
MainActivity extendsAppCompatActivity {
privateServiceConnectioncnn=newServiceConnection()
{
@Override
public voidonServiceConnected(ComponentName
componentName,IBinder iBinder) {
IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
try
{
iMyAidlInterface.addLog("add_demo");
String get = iMyAidlInterface.getLog("");
Log.d("main===",get+"");
}catch(RemoteException
e) {
e.printStackTrace();
}
}
@Override
public voidonServiceDisconnected(ComponentName
componentName) {
}
};
@Override
protected voidonCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent =newIntent(this,AIDLService.class);
bindService(intent,cnn,Context.BIND_AUTO_CREATE);
}
好了,我们运行一下程序,看看远程方法是否被调用
Log如下:
D/pspadd=====: add_demo
由此看来,远程方法已经成功调用,以上就是AIDL的简单用法。