Android序列化包括两种:Java的Serializable、Android自己的Parcelable。推荐使用Android系统自带的Parcelable。
Serializable方式
只需使对象实现Serialzable接口即可
假设Person类已经实现 Serializable接口
- 传输Person对象
intent.putExtra("person_data", person);
- 接收序列化对象
Person person = (Person) getIntent().getSerializableExtra("person_data");
Parcelable方式
Parcel :This class is designed as a high-performance IPC transport
Parcelable方式是把对象写成Parcel(小包),核心的类其实是Parcel。Parcelable定义的一系列接口就是是把对象分解成Parcel、把Parcel还原为对象。
Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface.
Parcelable除了该实现的抽象方法(分解对象为Parcel),还要必须要包含一个非空静态域,叫做CREATOR(把Parcel还原为对象)
public class Person implements Parcelable {
private String name;
private int age;
……
@Override
public int describeContents() {
return 0;
}
//写出对象为Parcel
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name); // 写出name
dest.writeInt(age); // 写出age
}
//非空静态域,还原Parcel为对象
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
//从Parcel还原
public Person createFromParcel(Parcel source) {
Person person = new Person();
person.name = source.readString(); // 读取name
person.age = source.readInt(); // 读取age
return person;
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
- 传输Person对象
intent.putExtra("person_data", person);
- 接收序列化对象
Person person = (Person) getIntent().getParcelableExtra("person_data");