使用Parcelable接口实现数据的序列化

Parcelable是Android中高效的数据序列化方法,优于Serializable。它适用于Intent数据传递和进程间通信(IPC)。实现步骤包括:实现Parcelable接口,重写writeToParcel和describeContents方法,以及创建静态内部CREATOR对象。尽管Parcelable性能优越,但在需要持久化数据时,推荐使用Serializable,以确保数据稳定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Parcelable是android中的方法,使用parcelable实现数据序列化的效率要比Serializable接口的效率更高,而且Parcelable可用于Intent数据传递也可用于进程间通信(IPC)

实现Parcelable接口的步骤:

1.implements Parcelable
2.重写writeToParcel方法,讲对象序列化为一个Parcel对象

public void writeToParcel(Parcel arg0, int arg1) {
		arg0.writeString(name);
		arg0.writeString(addr);
	}
3.重写describeContents方法,内容接口描述,默认返回0即可
4.实例化静态内部对象CREATOR实现接口Parcelable.Creator

public static final Parcelable.Creator<Station> CREATOR = new Parcelable.Creator<Station>() {
		public Station createFromParcel(Parcel arg0) {
			Station s = new Station();
			s.name = arg0.readString();
			s.addr = arg0.readString();
			return s;
		}


选择序列化方法的原则

1)在使用内存的时候,Parcelable比Serializable性能高,所以推荐使用Parcelable。

2)Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。

3)Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点,但此时还是建议使用Serializable


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值