【android实战经验】实现Parcelable接口进行对象序列化

Parcelable接口源码如下:

public interface Parcelable 
{
    //内容描述接口,基本不用管,一般返回0
    public int describeContents();
    //写入接口函数,打包
    public void writeToParcel(Parcel dest, int flags);
    //读取接口,目的是要从Parcel中构造一个实现了Parcelable的类的实例处理。因为实现类在这里还是不可知的,所以需要用到模板的方式,继承类名通过模板参数传入
    //为了能够实现模板参数的传入,这里定义Creator嵌入接口,内含两个接口函数分别返回单个和多个继承类实例
    public interface Creator<T> 
    {
           public T createFromParcel(Parcel source);
           public T[] newArray(int size);
    }
}

实现Parcelable接口步骤:

1. implements Parcelable;

2. 重写describContents()方法,用来描述接口内容,一般返回0

3. 重写writeToParcel()方法,用来将实现Parcelable的对象转成Parcel对象,进行序列化

4. 实现公共 静态 常量内部接口Parcelable.Creator<T>,重写内部的createFromParcel(),将Pacel对象转化为原来的对象,进行反序列化,注意读取顺序一定与writeToParcel()写入顺序一致重写内部的newArray()方法,newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话即可(return new T[size]),供外部类反序列化本类数组使用。


实现Parcelable的例子:

public class Person implements Parcelable {

	private String name;
	private boolean sex;
	private int phone;

	public Person() {} // 获取Parcel对象数据的构造方法

	public Person(String name, boolean sex, int phone) {// 外部提供写出数据的构造方法
		super();
		this.name = name;
		this.sex = sex;
		this.phone = phone;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel out, int flags) {
		out.writeString(name);
		out.writeInt(sex ? 1 : 0); // 因为Parcel对象的方法没有针对Boolean的写出方法,转成int型写出
		out.writeInt(phone);
	}

	public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {//注意Creator的对象名称必须是CREATOR
		@Override
		public Person[] newArray(int size) {//供外部类方便创建该Parcelable序列化类的数组
			return new Person[size];
		}

		@Override
		public Person createFromParcel(Parcel in) {//注意反序列化的顺序与序列化的顺序一致
			Person person = new Person();
			person.name = in.readString();
			person.sex = in.readInt() == 1 ? true : false;
			person.phone = in.readInt();

			return person;
		}
	};

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean getSex() {
		return sex;
	}

	public void setSex(boolean sex) {
		this.sex = sex;
	}

	public int getPhone() {
		return phone;
	}

	public void setPhone(int phone) {
		this.phone = phone;
	}

}


进行序列化的应用场景:

1)永久性保存对象,保存对象的字节序列到本地文件中;

2)通过序列化对象在网络中传递对象;

3)通过序列化在跨进程间传递对象。


参考网址:http://www.cnblogs.com/renqingping/archive/2012/10/25/Parcelable.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值