android存储那块的ContentValue源码中用到了Parcelable接口。这个接口的功能主要是为了对象的序列化。序列化的作用大概应该都清楚。
1、永久性保存对象,保存对象的字节序列到本地文件中。
2、通用序列化对象在网络中传递对象。
3、通过序列化在进程间传递对象。
我们平时用到最多的序列化接口都是Serializable接口,这个是JavaSe这块的内容,我们都非常熟悉。
两者的优劣,我看了网上解析并总结了使用场景:
1、在进程间传递对象,这个建议用Parcelable接口,Parcelable在内存处理上更高效,用Bundle在activity间进行通信,Bundle有一个方法Bundle.putParcelable(key,Object)。它也支持Bundle.putSerializable(key,Object)。
因为Parcelable接口在内存的处理上更加高效,Serializable接口在序列化的过程中会产生大量的临时变量。
2、永久保存本地和在网络中传递对象时,还是建议实现Serializable接口,因为当外界的序列化的东西变化了,Parcelable接口实现时不能很好的适应。
在实现Parcelable时需要实现下面两个接口
/** * Describe the kinds of special objects contained in this Parcelable's * marshalled representation. * * @return a bitmask indicating the set of special object types marshalled * by the Parcelable. */ public int describeContents(); /** * Flatten this object in to a Parcel. * * @param dest The Parcel in which the object should be written. * @param flags Additional flags about how the object should be written. * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}. */ public void writeToParcel(Parcel dest, int flags);