安卓开发-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方法则用于告诉平台如何将该类的实例存储到包裹中。通过这种约定,平台就知道怎么序列化和反序列化了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不吃鸳鸯锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值