1. Serializable方式
Serializable是序列化的意思,含义是将一个对象转化为可存储或是可传输的状态,序列化后的对象可以在网络上进行传输,也可以存储到本地。
private void serializeData() {
Person person = new Person();
person.setAge(1);
person.setName("TOM");
Intent intent = new Intent(this, SerializableTestActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
}
private void deSerializeData() {
Person person = (Person) getIntent().getSerializableExtra("person_data");
}
public class Person implements Serializable {
private String name;
private int age;
geterAndSetter(){
......
}
}
2 Parcelable方式
Parcelable 方式也可以用于传递对象,不同于序列化,Parcelable是将一个完整的对象进行分解,其每一部分都是intent支持的数据类型
public class Person implements Parcelable{
private String name;
private int age;
protected Person(Parcel in) {
name = in.readString();
age = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
@Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
private void getParseData() {
Person person = (Person) getIntent().getParcelableExtra("person_data");
}