Android开发中包裹机制的实例分析

来源:爱站网时间:2020-08-13编辑:网友分享
Parcel是一种新的序列化机制,不同于Android中的Java序列化,而Java序列化机制的功能是将数据对象存储到字节流中,并在需要时重新生成它们,这篇文章是爱站技术频道小编为大家带来的Android开发中包裹机制的实例分析,一起来了解吧!

Parcel是一种新的序列化机制,不同于Android中的Java序列化,而Java序列化机制的功能是将数据对象存储到字节流中,并在需要时重新生成它们,这篇文章是爱站技术频道小编为大家带来的Android开发中包裹机制的实例分析,一起来了解吧!

本文实例讲述了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实现长按键退出应用程序

下一篇:Android服务重启的方法

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载