基于Android AIDL进程间通信接口使用介绍

时间:2022-07-02 07:42:46

aidl:android interface definition language,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口。

icp:interprocess communication ,内部进程通信。

使用:

1、先创建一个aidl文件,aidl文件的定义和java代码类似,但是!它可以引用其它aidl文件中定义的接口和类,但是不能引用自定义的java类文件中定义的接口和类,要引用自定义的接口或类,需要为此类也定义一个对应的aidl文件,并且此类要实现parcelable接口,同时aidl文件和类文件必须要在相同包下进行声明;android包含了aidl编译器,当定义好一个aidl文件的时候,会自动编译生成一个java文件,此文件保存在gen目录之下。

基于Android AIDL进程间通信接口使用介绍

 

在这个项目中,定义了两个aidl文件,其中person实现了接口parcelable,下面是这两个aidl文件的定义:

person.aidl

{

parcelable person; 

}

iaidlserverservice.aidl

{

  package com.webview;
  import com.webview.person;// 引用上面的person.aidl

  interface iaidlserverservice{
    string sayhello();
    person getperson();
  }

}

2、编写一个service实现定义aidl接口中的内部抽象类stub,stub继承自binder,并继承我们在aidl文件中定义的接口,我们需要实现这些方法。stub中文意思存根,stub对象是在服务端进程中被调用,即服务端进程。

在客户端调用服务端定义的aidl接口对象,实现service.onbind(intent)方法,该方法会返回一个ibinder对象到客户端,绑定服务时需要一个serviceconnection对象,此对象其实就是用来在客户端绑定service时接收service返回的ibinder对象。

  ||public static abstract class stub extends android.os.binder implements com.webview.iaidlserverservice

?
1
public class aidlserverservice extends service{@overridepublic ibinder onbind(intent intent) {return binder;}private iaidlserverservice.stub binder = new stub() {@overridepublic string sayhello() throws remoteexception {return "hello aidl";}@overridepublic person getperson() throws remoteexception {person person = new person();person.setname("livingstone");person.setage(22);return person;}};}

3、在服务端注册service,将如下代码添加进application节点之下!

<service android:name="com.webview.aidlserverservice"
  android:process=":remote">
  <intent-filter>
    <action android:name="com.webview.iaidlserverservice"></action>
  </intent-filter>
</service>

至此,服务端进程定义已经完成!

4、编写客户端,注意需要在客户端存一个服务端实现了的aidl接口描述文件,客户端只是使用该aidl接口,获取服务端的aidl对象(iaidlserverservice.stub.asinterface(service))之后就可以调用接口的相关方法,而对象的方法的调用不是在客户端执行,而是在服务端执行。

?
1
public class mainactivity extends activity {private button btn;private iaidlserverservice aidlservice = null;<br>private serviceconnection conn = new serviceconnection() {@overridepublic void onservicedisconnected(componentname name) {aidlservice = null;}@overridepublic void onserviceconnected(componentname name, ibinder service) {aidlservice = iaidlserverservice.stub.asinterface(service);try {aidlservice.dofunction();// 执行接口定义的相关方法} catch (remoteexception e) {e.printstacktrace();}}};@overrideprotected void oncreate(bundle savedinstancestate) {super.oncreate(savedinstancestate);setcontentview(r.layout.activity_main);btn = (button) findviewbyid(r.id.button);tv = (textview) findviewbyid(r.id.textview);btn.setonclicklistener(new onclicklistener() {@overridepublic void onclick(view v) {intent service = new intent("com.webview.iaidlserverservice");bindservice(service, conn, bind_auto_create);// 绑定服务}});}}

 客户端目录结构:

基于Android AIDL进程间通信接口使用介绍

相关文章