AIDL是安卓接口定义语言的简称,用于进程间通信 ,
AIDL默认支持的数据类型有:八种基本数据类型、String、List
如果要使用AIDL传递类对象,就必须让类实现Parcelable接口
文件结构如图所示
people.java
- public class People implements Parcelable {
- String name;
- int age;
-
- public People(int age,String name){
- this.age = age;
- this.name = name;
- }
- public People(Parcel in) {
- name = in.readString();
- age = in.readInt();
- }
-
- public static final Creator
CREATOR = new Creator() { - @Override
- public People createFromParcel(Parcel in) {
- return new People(in);
- }
-
- @Override
- public People[] newArray(int size) {
- return new People[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(name);
- dest.writeInt(age);
- }
- }
people.aidl
- package com.example.aidl;
- parcelable People;
IPeopleManager.aidl
- package com.example.aidl;
-
- // Declare any non-default types here with import statements
- import com.example.aidl.People;
- interface IPeopleManager {
- /**
- * 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);
-
- int getAge();
- String getName();
- void addPeople(in People people);
- }
aidl方法传入自定义类对象时,in、out、inout必须写(aidl默认支持的类型不用写,默认且只能是in),否则报错。
.27-34: 'com.example.aidl.People' can be an out type, so you must declare it as in, out, or inout.
关于参数前的in、out和inout,跨进程时,in参数会把参数的内容传给aidl,但其改动不会同步到调用进程;out参数不会把参数的属性传给aidl(aidl获取的参数对象属性为空),但其改动会同步到调用进程;inout参数则是in和out的综合。不跨进程时,三者则是摆设
然后编译项目,如果提示找不到符号
public void addPeople(com.example.aidl.People people) throws android.os.RemoteException;
则需要在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']
- }
- }