今天讲android AIDL的IPC传递对象,可以通过AIDL来实现跨进程传递对象。另外,会讲Parcelable接口,如果要实现在IPC传递对象,对象必须实现Parcelable接口。
以下是android developer的讲解:
通过 IPC 传递对象
通过 IPC 接口把某个类从一个进程发送到另一个进程是可以实现的。 不过,您必须确保该类的代码对 IPC 通道的另一端可用,并且该类必须支持 Parcelable 接口。支持 Parcelable 接口很重要,因为 Android 系统可通过它将对象分解成可编组到各进程的原语。
如需创建支持 Parcelable 协议的类,您必须执行以下操作:
- 让您的类实现 Parcelable 接口。
- 实现 writeToParcel,它会获取对象的当前状态并将其写入 Parcel。
- 为您的类添加一个名为 CREATOR 的静态字段,这个字段是一个实现 Parcelable.Creator 接口的对象。
- 最后,创建一个声明可打包类的 .aidl 文件(按照下文 Rect.aidl 文件所示步骤)。
如果您使用的是自定义编译进程,切勿在您的编译中添加 .aidl 文件。 此 .aidl 文件与 C 语言中的头文件类似,并未编译。
AIDL 在它生成的代码中使用这些方法和字段将您的对象编组和取消编组。
例如,以下这个 Rect.aidl 文件可创建一个可打包的 Rect 类:
package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable Rect;
以下示例展示了 Rect 类如何实现 Parcelable 协议。
import android.os.Parcel;
import android.os.Parcelable;
public final class Rect implements Parcelable {
public int left;
public int top;
public int right;
public int bottom;
public static final Parcelable.Creator<Rect> CREATOR = new
Parcelable.Creator<Rect>() {
public Rect createFromParcel(Parcel in) {
return new Rect(in);
}
public Rect[] newArray(int size) {
return new Rect[size];
}
};
public Rect() {
}
private Rect(Parcel in) {
readFromParcel(in);
}
public void writeToParcel(Parcel out) {
out.writeInt(left);
out.writeInt(top);
out.writeInt(right);
out.writeInt(bottom);
}
public void readFromParcel(Parcel in) {
left = in.readInt();
top = in.readInt();
right = in.readInt();
bottom = in.readInt();
}
}
Rect 类中的编组相当简单。看一看 Parcel 上的其他方法,了解您可以向 Parcel 写入哪些其他类型的值。
警告:别忘记从其他进程接收数据的安全影响。 在本例中,Rect 从 Parcel 读取四个数字,但要由您来确保无论调用方目的为何这些数字都在相应的可接受值范围内。 如需了解有关如何防止应用受到恶意软件侵害、保证应用安全的更多信息,请参见 安全与权限。