分享好友 移动开发首页 频道列表

Android开发之Parcel机制实例分析

Android开发  2015-06-26 11:100

本文实例讲述了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开发】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
SDK热更之如何在SDK代码中自动插桩及如何生成补丁包
写在前面本文是SDKHotfix相关的SDK热更系列文章中的一篇,以下为项目及系列文章相关链接:SDKHotfix整体介绍:http://blog.bihe0832.com/sdk_hotfix_project.htmlSDKHotfix对应github地址:https://github.com/bihe0832/SDKHoxFix这篇文章主要介绍一下SDK热更

0评论2017-02-05358

Supporting Multiple Screens
术语和概念Screen size 屏幕尺寸又称「屏幕大小」,是屏幕对角线的物理尺寸。单位英寸 inch,比如 Samsung Note4 是 5.7 英寸。Resolution 屏幕分辨率屏幕纵横方向上物理像素的总数,比如 Samsung Note4 是 2560x1440,表示纵向有 2560 个像素,横向有 1440

0评论2017-02-05363

AssetBundle里的Shader问题
关于Resources和AssetBundle优劣之前已经提过很多次了(参考官方教程The Resources folder),正好最近@张迪在做框架AssetBundle部分的优化,特此整理一下两个特常见的坑及对应解决办法。之前在关于Unity中的资源管理,你可能遇到这些问题里有有人提到过这个问

0评论2017-02-05610

ASimpleCache
ASimpleCache 是一个为android制定的 轻量级的 开源缓存框架。轻量到只有一个java文件(由十几个类精简而来)。1、它可以缓存什么东西?普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java对象,和 byte数据。2、它有什么特色?特色主要是

0评论2017-02-05376

更多推荐