读书人

Android接口定义语言-AIDL(3)

发布时间: 2012-09-21 15:47:26 作者: rapoo

Android接口定义语言---AIDL(三)

在IPC通道上传递对象

如果要通过IPC接口把一个类从一个进程发送到另一个进程,这是可以做到的。但是必须确保该类的代码对应IPC通道另一侧的进程是可用的,并且该类必须支持Parcelable接口。支持Parcelable接口是重要的,因为它允许Android系统把对象分解成能够跨进程进行编组的原始类型。

必须按照以下步骤来创建一个支持Parcelable协议的类:

1. 要让该类实现Parcelable接口;

2. 实现writeToParcel接口,它会携带该对象的当前状态并把它写入Parcel;

3. 给该类添加一个叫做CREATOR的字段,它是一个实现了Parcelable.Creator接口的对象;

4. 最后,创建一个声明可打包类的.aidl文件(如下所示的Rect.aidl文件);

如果要使用一个定制的编译过程,没有添加对.aidl文件的编译,那么类似C语言中的头文件,这个.aidl文件不会被编译。

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中读取四个数字,但是无论调用者试图做什么,可接收的值的范围都必须你来确保。关于如何保护软件免受恶意攻击的更多信息,请看“安全和权限”

http://developer.android.com/guide/topics/security/permissions.html

读书人网 >网络基础

热点推荐