今天小编给大家精心推荐个基于Android AIDL进程间通信接口使用介绍教程,一起来看看过程究竟如何进行吧!喜欢还请点个赞哦~
Definition Language,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口。
Communication ,内部进程通信。
使用:
1、先创建一个aidl文件,aidl文件的定义和java代码类似,但是!它可以引用其它aidl文件中定义的接口和类,但是不能引用自定义的java类文件中定义的接口和类,要引用自定义的接口或类,需要为此类也定义一个对应的aidl文件,并且此类要实现Parcelable接口,同时aidl文件和类文件必须要在相同包下进行声明;Android包含了aidl编译器,当定义好一个aidl文件的时候,会自动编译生成一个java文件,此文件保存在gen目录之下。
在这个项目中,定义了两个aidl文件,其中Person实现了接口Parcelable,下面是这两个aidl文件的定义:
{
parcelable Person;
}
{
package ;
import .Person;// 引用上面的
interface IAIDLServerService{
String sayHello();
Person getPerson();
}
}
2、编写一个Service实现定义aidl接口中的内部抽象类Stub,Stub继承自Binder,并继承我们在aidl文件中定义的接口,我们需要实现这些方法。Stub中文意思存根,Stub对象是在服务端进程中被调用,即服务端进程。
在客户端调用服务端定义的aidl接口对象,实现()方法,该方法会返回一个对象到客户端,绑定服务时需要一个对象,此对象其实就是用来在客户端绑定时接收返回的对象。
||public static abstract class Stub extends implements .IAIDLServerService
public class AIDLServerService extends[email protected]IBinder onBind(Intent intent) {return binder;}private binder = new Stub()[email protected]String sayHello() throws RemoteException {return "Hello AIDL";[email protected]Person getPerson() throws RemoteException {Person person = new Person();("")() person;}};}
3、在服务端注册Service,将如下代码添加进Application节点之下!
service android:name=".AIDLServerService"
""
intent-filter
action android:name=".IAIDLServerService"/action
/intent-filter
/service
至此,服务端进程定义已经完成!
4、编写客户端,注意需要在客户端存一个服务端实现了的aidl接口描述文件,客户端只是使用该aidl接口,获取服务端的aidl对象(.asInterface(service))之后就可以调用接口的相关方法,而对象的方法的调用不是在客户端执行,而是在服务端执行。
public class MainActivity extends Activity {private Button btn;private IAIDLServerService aidlService = null;
private ServiceConnection conn = new ServiceConnection()[email protected]void onServiceDisconnected(ComponentName name) {aidlService = null;[email protected]void onServiceConnected(ComponentName name, IBinder service) {aidlService = .asInterface(service);try {() 执行接口定义的相关方法} catch (RemoteException e) {()}}} void onCreate(Bundle savedInstanceState) {()() = (Button) findViewById();tv = (TextView) findViewById();(new OnClickListener()[email protected]void onClick(View v) {Intent service = new Intent(".IAIDLServerService");bindService(service, conn, BIND_AUTO_CREATE);// 绑定服务}});}}
客户端目录结构: