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