1.序列化的两种方式
(1) 实现了Serializable--java自带的序列化接口
(2) 实现Parcelable接口,Android中的序列化接口,效率较高
2.不同序列化接口的具体用法
public class SerializableBean implements Serializable {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ParcelableBean implements Parcelable {
private int age;
private String name;
protected ParcelableBean(Parcel in) {
age = in.readInt();
name = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
}
@Override
public int describeContents() {
// 只有在对象中存在文件描述符时,此方法才返回1
return 0;
}
public static final Creator<ParcelableBean> CREATOR = new Creator<ParcelableBean>() {
@Override
public ParcelableBean createFromParcel(Parcel in) {
return new ParcelableBean(in);
}
@Override
public ParcelableBean[] newArray(int size) {
return new ParcelableBean[size];
}
};
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.使用Intent传递的方式
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
获取方式的不同
(Person) getIntent().getSerializableExtra("person_data");
(Person) getIntent().getParcelableExtra("person_data");