在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