当前位置: 移动技术网 > IT编程>移动开发>Android > Android IPC进程间通信详解最新AndroidStudio的AIDL操作)

Android IPC进程间通信详解最新AndroidStudio的AIDL操作)

2019年07月24日  | 移动技术网IT编程  | 我要评论

前言

前面梳理了android的线程间的通信《thread、handler和handlerthread关系何在?》 ,这些都是在同一个进程中,那进程间的通信,或者说不同的应用间的通信该如何实现呢?这个时候就要用到aidl(android interface definition languageandroid接口定义语言 )。

使用方法(androidstudio)

我发现现在aidl的教程基本上还是eclipse的,但是在androidstudio里面使用aidl还是有一些不同的,来看看怎么用,首先新建一个工程当做server服务端:

创建好后在任意文件夹右键new-->aidl-->aidl file,编辑文件名后会自动在src/main目录下面新建aidl文件夹,包的目录结构如下:

main
aidl
com.example.tee.testapplication.aidl
java
com.example.tee.testapplication
res
androidmanifest.xml

自动生成的aidl文件如下:

// aidlinterface.aidl
package com.example.tee.testapplication.aidl;

// declare any non-default types here with import statements

interface aidlinterface {
 /**
 * demonstrates some basic types that you can use as parameters
 * and return values in aidl.
 */
 void basictypes(int anint, long along, boolean aboolean, float afloat,
 double adouble, string astring);
}

我们可以看到aidl文件的代码格式跟java很像,支持java的基础类型以及list、map等,如果是自定义类的话需要手动导入,我们后面再说,先来最简单的,新建一个 imyaidlinterface.aidl文件,修改如下:

package com.example.tee.testapplication.aidl;

interface imyaidlinterface {
 string getvalue();
}

在接口中定义一个getvalue方法,返回一个字符串,现在可以编译一下工程,找到app/build/generated/source/aidl/debug目录,在我们应用包名下会发现生成了一个interface类,名字跟我们定义的aidl的文件名字一样,这说明其实aidl文件在最后还是会转换成接口来实现,而且这个文件不需要我们维护,在编译后自动生成。

然后新建一个类继承service:

public class maidlservice extends service{
 public class maidlserviceimpl extends imyaidlinterface.stub{
 @override
 public string getvalue() throws remoteexception {
 return "get value";
 }
 }
 @nullable
 @override
 public ibinder onbind(intent intent) {
 return new maidlserviceimpl();
 }
}

在maidlservice类中定义一个内部类继承imyaidlinterface.stub,并且重写我们在aidl也就是在接口中定义的getvalue方法,返回字符串get value。

到了这里,我们就新建好了这个服务端,作用是在调用后返回一个字符串,最后在androidmanifest文件中声明:

<service
 android:name=".maidlservice"
 android:process=":remote"//加上这句的话客户端调用会创建一个新的进程
 android:exported="true"//默认就为true,可去掉,声明是否可以远程调用
 >
 <intent-filter>
 <category android:name="android.intent.category.default" />
 <action android:name="com.example.tee.testapplication.aidl.imyaidlinterface" />
 </intent-filter>
</service>

android:process=":remote"这一行的作用是声明是否调用时新建进程,接下来写客户端代码,新建一个工程,将刚才创建的aidl文件拷贝到这个工程中,注意同样也是要放在aidl文件夹下,然后在mainactivity中编写代码如下:

public class mainactivity extends appcompatactivity {
 private textview mvaluetv;
 private imyaidlinterface maidlinterface = null;
 private serviceconnection mserviceconnection = new serviceconnection() {
 @override
 public void onserviceconnected(componentname name, ibinder service) {
 maidlinterface = imyaidlinterface.stub.asinterface(service);
 }

 @override
 public void onservicedisconnected(componentname name) {

 }
 };
 @override
 protected void oncreate(bundle savedinstancestate) {
 intent intent = new intent("com.example.tee.testapplication.aidl.imyaidlinterface");
 bindservice(intent, mserviceconnection, bind_auto_create);
 mvaluetv = (textview) findviewbyid(r.id.tv_test_value);
 mvaluetv.setonclicklistener(new view.onclicklistener() {
 @override
 public void onclick(view v) {
 try {
  mvaluetv.settext(maidlinterface.getvalue());
 } catch (remoteexception e) {
  e.printstacktrace();
 }
 }
 });
 }

 @override
 protected void ondestroy() {
 if(maidlinterface != null){
 unbindservice(mserviceconnection);
 }
 super.ondestroy();
 }
}

注意这里新建intent的传入的参数字符串是在manifest里面自定义的action标签,并且在ondestroy记得取消绑定服务。

执行结果就是我们在点击textview时会显示服务端给我们返回的get value字符串

自定义的对象

刚才我们使用的是基础类型string,在使用我们自己定义的类的时候用上面的方法是不行的,用我们自定义的类需要手动导入,修改刚才我们创建的作为服务端的工程

首先在开始生成的aidl包下(所有aidl相关的文件都要放在这个包下)新建student.java

public class student implements parcelable{
 public string name;
 public int age;
 protected student(parcel in) {
 readfromparcel(in);
 }
 public student() {
 }

 public static final creator<student> creator = new creator<student>() {
 @override
 public student createfromparcel(parcel in) {
 return new student(in);
 }

 @override
 public student[] newarray(int size) {
 return new student[size];
 }
 };

 @override
 public int describecontents() {
 return 0;
 }

 @override
 public void writetoparcel(parcel dest, int flags) {
 dest.writeint(age);
 dest.writestring(name);
 }

 public void readfromparcel(parcel in){
 age = in.readint();
 name = in.readstring();
 }

 @override
 public string tostring() {
 return string.format(locale.english, "student[%s:%d]", name, age);
 }
}

需要实现parcelable序列化接口,androidstudio会自动生成静态内部类creator和describecontents方法,这些部分我们都不需要修改,用自动生成的就好。然后重写writetoparcel方法,自定义readfromparcel方法,注意这两个方法里面的属性顺序必须一致,一个是写入,一个是读取。在构造方法student(parcel in)中调用readfromparcel(in)方法。

接下来新建student.aidl文件(也是在aidl包中):

// student.aidl
package com.example.tee.testapplication.aidl;

// declare any non-default types here with import statements
parcelable student;

注意这里student前面的关键字parcelable首字母是小写哦,再修改imyaidlinterface.aidl文件如下:

// imyaidlinterface.aidl
package com.example.tee.testapplication.aidl;

// declare any non-default types here with import statements
import com.example.tee.testapplication.aidl.student;

interface imyaidlinterface {
 student getstudent();
 void setstudent(in student student);
 string getvalue();
}

定义了两个方法,一个是设置student,一个是获取student,在setstudent这个方法注意参数在类型前面有个in关键字,在aidl里参数分为in输入,out输出

现在在maidlservice.java中重写新加的两个方法:

private student mstudent;
public class maidlserviceimpl extends imyaidlinterface.stub{


 @override
 public student getstudent() throws remoteexception {
 return mstudent;
 }

 @override
 public void setstudent(student student) throws remoteexception {
 mstudent = student;
 }

 @override
 public string getvalue() throws remoteexception {
 return "get value : " + thread.currentthread().getname() + thread.currentthread().getid();
 }
}

服务端代码修改完毕,来到客户端工程,同样要把刚才的aidl包下的文件拷贝覆盖过来,保持两边一致,然后在mainactivity.java中修改如下:

mvaluetv = (textview) findviewbyid(r.id.tv_test_value);
mstudenttv = (textview) findviewbyid(r.id.tv_test_student);
mvaluetv.setonclicklistener(new view.onclicklistener() {
 @override
 public void onclick(view v) {
 try {
 mvaluetv.settext(maidlinterface.getvalue());
 } catch (remoteexception e) {
 e.printstacktrace();
 }
 }
});
mstudenttv.setonclicklistener(new view.onclicklistener() {
 @override
 public void onclick(view v) {
 try {
 student student = new student();
 student.age = 10;
 student.name = "tom";
 maidlinterface.setstudent(student);
 mstudenttv.settext(maidlinterface.getstudent().tostring());
 } catch (remoteexception e) {
 e.printstacktrace();
 }
 }
});

现在编译工程,会发现工程会报错,找不到类student,我们需要在app目录下的build.gradle文件添加代码如下:

android {
 sourcesets {
 main {
 manifest.srcfile 'src/main/androidmanifest.xml'
 java.srcdirs = ['src/main/java', 'src/main/aidl']
 resources.srcdirs = ['src/main/java', 'src/main/aidl']
 aidl.srcdirs = ['src/main/aidl']
 res.srcdirs = ['src/main/res']
 assets.srcdirs = ['src/main/assets']
 }
 }
}

也就是指定一下文件目录,现在再编译就没有问题了

总结

android的ipc使用起来还是挺简单的,aidl文件的语法也跟我们平时使用接口的时候很相似,但是它只支持基础类型,只能引用aidl文件,需要使用自定义类的时候要稍微麻烦一点。

以上就是对android ipc 进程通信的资料整理,后续继续补充相关资料谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网