parcel和parcelable

时间:2022-04-25
本文章向大家介绍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;  
     }  
 }