在android中经常要使用到进程间通信传输数据,基本都是使用Intent指向须跳转的页面。
传送数据的无外乎有bundle,或者直接在intent里putextra(key,value);
基本类型可以直接传递,但需要传输对象的时候就不支持了。
这时需要我们将对象序列化,这边先试下parcel的。只要将对象实现parcelable接口,
重写几个方法即可。
如下:
package com.nico;
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
public Person() {
}
String name = "";
String country = "";
public Person(Parcel source) {
//属性
this.name = source.readString();
this.country = source.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
//写入属性 ,源activity中序列化好对象
arg0.writeString(this.name);
arg0.writeString(this.country);
}
//进程间通信必须要使用该属性
public final static Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
//在新的context中返回序列化好的对象
return new Person(source);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
传递list或者map时,主要集合中的对象都是序列化好的,皆可传递。