一、APP客户端进程与后台服务进程的AIDL通信
AIDL(Android Interface definition language-“接口定义语言”) 是 Android 提供的一种进程间通信 (IPC:Inter-Process Communication) 机制,支持的数据类型:
1. Java 的原生类型;
2. String 和CharSequence;
3. List 和 Map ,List和Map 对象的元素必须是AIDL支持的数据类型; 以上三种类型都不需要导入(import);
4. AIDL 自动生成的接口 需要导入(import);
5. 实现android.os.Parcelable 接口的类. 需要导入(import)。
Android studio工程建立如下:
app和remoteserver按常规应用建立,remoteservicecontract通过新建Android Library生成:
也可以将原本的应用模块改成库模块:
然后在remoteservicecontract建立aidl目录并新建AIDL文件:
建立如下三个AIDL接口:
aidl文件的声明和java实现如下:
(1)Entity.aidl 是声明本地实现的 android.os.Parcelable 接口的类
// Entity.aidl package com.example.remoteserver; parcelable Entity;
java实现:
package com.example.remoteserver; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; public class Entity implements Parcelable { private int age; private String name; private final String TAG = "Engity"; public Entity() { } public Entity(int age, String name) { Log.i(TAG,"new age="+age+",name="+name); this.age = age; this.name = name; } protected Entity(Parcel in) { age = in.readInt(); name = in.readString(); } public static final Creator<Entity> CREATOR = new Creator<Entity>() { @Override public Entity createFromParcel(Parcel in) { return new Entity(in); } @Override public Entity[] newArray(int size) { return new Entity[size]; } }; public int getAge() { Log.i(TAG,"get age="+age); return this.age; } public void setAge(int age) { Log.i(TAG,"set age="+age); this.age = age; } public String getName() { Log.i(TAG,"get name="+name); return this.name; } public void setName(String name) { Log.i(TAG,"set name="+name); this.name = name; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(age); dest.writeString(name); } @Override public String toString() { return String.format("age=%s, name=%s", getAge(), getName()); } }
(2)IRemoteService.aidl声明服务端供客户端调用的接口:
// IRemoteService.aidl package com.example.remoteserver; import com.example.remoteserver.Entity; import com.example.remoteserver.ITVCallback; // Declare any non-default types here with import statements interface IRemoteService { void doSomeThing(int anInt,String aString); void addEntity(in Entity entity); void setEntity(int index,in Entity entity); List<Entity> getEntity(); void asyncCallSomeone( String para, ITVCallback callback); }
java实现: