您的位置:首页 > 移动开发 > Android开发

Android开发之Parcel机制实例分析

2015-05-27 11:51 2076 查看

本文实例讲述了Android开发之Parcel机制。分享给大家供大家参考。具体分析如下:

在java中,有序列化机制。但是在安卓设备上,由于内存有限,所以设计了新的序列化机制。

Container for a message (data and object references) that can be sent through an IBinder.  A Parcel can contain both flattened data that will be unflattened on the other side of the IPC (using the various methods here for writing specific types, or the generalParcelable interface), and references to liveIBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.

Parcel is not a general-purpose serialization mechanism.  This class (and the correspondingParcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport.  As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.

从上面的官方解释可以看到,Parcel主要就是用来序列化,在一端编码,在另外一端进行解码。

本质上把它当成一个Serialize就可以了,只是它是在内存中完成的序列化和反序列化,利用的是连续的内存空间,因此会更加高效。

我们接下来要说的是Parcel类如何应用。就应用程序而言,最常见使用Parcel类的场景就是在Activity间传递数据。没错,在Activity间使用Intent传递数据的时候,可以通过Parcelable机制传递复杂的对象。

具体例子可以参见这里,写的很好。

在实现Parcelable接口的时候,必须实现其中的两个方法并且定义一个CREATOR:

@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(color);
}

其中,writeToParcel方法定义了怎么向序列化中写入该类对象的信息。

CREATOR对象中定义了两个函数:

public MyColor createFromParcel(Parcel in) {
return new MyColor(in);
}
public MyColor[] newArray(int size) {
return new MyColor[size];
}

其中,createFromParcel方法告诉平台如何从已经序列化的对象中构建该类的实例。newArray方法的作用不明。实现于Parcelable接口的CREATOR成员的createFromParcel方法用于告诉平台如何从包裹里创建该类的实例,而writeToParcel方法则用于告诉平台如何将该类的实例存储到包裹中。通过这种约定,平台就知道怎么序列化和反序列化了。

希望本文所述对大家的Android程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android Parcel