Android介面定義語言—AIDL(三)

來源:互聯網
上載者:User

在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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.