Parcel是一个轻量级的对象序列化,(类似Serierlizable), 可用于进程间通信,用的时候需要写个static CREATOR, 写入数据和读出的顺序必需一致。
研究了下怎么样传送List<T>, 下面这个例子直接传ArrayList<String>:
public class MyParcelInfo implements Parcelable {
private int feildCount;
private ArrayList<String> feildNameList;
public MyParcelInfo(Parcel in) {
feildCount = in.readInt();
feildNameList = new ArrayList<String>();
in.readList(feildNameList, ClassLoader.getSystemClassLoader());
}
public MyParcelInfo() {
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(feildCount);
dest.writeList(feildNameList);
}
public static final Parcelable.Creator<MyParcelInfo> CREATOR = new Parcelable.Creator<MyParcelInfo>() {
public MyParcelInfo createFromParcel(Parcel in) {
return new MyParcelInfo(in);
}
public MyParcelInfo[] newArray(int size) {
return new MyParcelInfo[size];
}
};
public void setFeildCount(int count) {
this.feildCount = count;
}
public int getFeildCount() {
return this.feildCount;
}
public ArrayList<String> getFeildList() {
return this.feildNameList;
}
public void setFeildList(ArrayList<String> list){
this.feildNameList = list;
}
}
下面是发送代码:
protected void sendParcel() {
MyParcelInfo info = new MyParcelInfo();
info.setFeildCount(4);
ArrayList<String> list = new ArrayList<String>();
list.add("Lisp");
list.add("JNI");
list.add("Net");
list.add("Box2d");
info.setFeildList(list);
Intent it = new Intent(MainActivity.this, ParcelReceiverActivity.class);
it.putExtra("info", info);
this.startActivity(it);
}
下面是接收代码:
MyParcelInfo info = this.getIntent().getParcelableExtra("info");
ArrayList<String> infoList = info.getFeildList();
和String一样,如下的类型可以传送:
- null
- String
- Byte
- Short
- Integer
- Long
- Float
- Double
- Boolean
- String[]
- boolean[]
- byte[]
- int[]
- long[]
- Object[] (supporting objects of the same type defined here).
Bundle
- Map (as supported by
writeMap
). - Any object that implements the
Parcelable
protocol. - Parcelable[]
- CharSequence (as supported by
TextUtils.writeToParcel
). - List (as supported by
writeList
). SparseArray
(as supported bywriteSparseArray
).IBinder
- Any object that implements Serializable (but see
writeSerializable
for caveats). Note that all of the previous types have relatively efficient implementations for writing to a Parcel; having to rely on the generic serialization approach is much less efficient and should be avoided whenever possible.
parcel可以用于Activity之间传送对象,相比于用Bundle传送,Parcel的好处是可以把数据打包成对象传送,可读性和可维性比用Bundle传一大堆Key,Value键值对要好,同时也可以扩展为传递其它类型的对象(implements Serializalbe or Parcelable).
关于进程间通信的应用,有待进一步研究。