天天看點

parcel和parcelable

parcel 在英文中有兩個意思,其一是名詞,為包裹,小包的意思; 其二為動詞,意為打包,紮包。郵寄快遞中的包裹也用的是這個詞。android采用這個詞來表示封裝消息資料。這個是通過ibinder通信的消息的載體。需要明确的是parcel用來存放資料的是記憶體(ram),而不是永久性媒體(nand等)。

parcelable,定義了将資料寫入parcel,和從parcel中讀出的接口。一個實體(用類來表示),如果需要封裝到消息中去,就必須實作這一接口,實作了這一接口,該實體就成為“可打包的”了。

接口的定義如下:

public interface parcelable {  

    //内容描述接口,基本不用管  

    public int describecontents();  

    //寫入接口函數,打包  

    public void writetoparcel(parcel dest, int flags);  

     //讀取接口,目的是要從parcel中構造一個實作了parcelable的類的執行個體處理。因為實作類在這裡還是不可知的,是以需要用到模闆的方式,繼承類名通過模闆參數傳入。  

    //為了能夠實作模闆參數的傳入,這裡定義creator嵌入接口,内含兩個接口函數分别傳回單個和多個繼承類執行個體。  

    public interface creator<t> {  

           public t createfromparcel(parcel source);  

           public t[] newarray(int size);  

       }  

在實作parcelable的實作中,規定了必須定義一個靜态成員, 初始化為嵌入接口的實作類。

public static parcel.creator<drievedclassname>  creator =  

    new parcel.creator<drievedclassname>();   

下面定義了一個簡單類mymessage, 他需要把自身的資料mdata,打入包中。 同時在消息的接收方需要通過mymessage實作的parcelable接口,将mymessage重新構造出來。

import android.os.parcel;  

import android.os.parcelable;  

public class mymessage implements parcelable {  

    private int mdata;  

    public int describecontents() {  

        return 0;  

    }  

    public void writetoparcel(parcel out, int flags) {  

        out.writeint(mdata);  

    public static final parcelable.creator<mymessage> creator  

           = new  parcelable.creator<mymessage>(){  

        public mymessage createfromparcel(parcel in) {  

            return new mymessage(in);  

        }  

        public mymessage[] newarray(int size) {  

            return new mymessage[size];  

    };  

    private mymessage(parcel in) {  

        mdata = in.readint();  

    public mymessage(int data) {  

    // todo auto-generated constructor stub  

    mdata = data;  

}  

繼續閱讀