Using the Android Parcel
Parcel 是一种轻量级高效率的Inter-process communication (IPC)通信机制.使用Parcels,android系统可以将实体对象分解为可以在进程之间传递的基元对象。
Parcels同样可以进程之内的数据传输,例如,一个android有多个activities,activity之间使用Intent传递数据User,例如
// inside CollectDataActivity, construct intent to pass along the next Activity, i.e. screen Intent in = new Intent(this, ProcessDataActivity.class); in.putExtra("userid", id); // (key,value) pairs in.putExtra("age", age); in.putExtra("phone", phone); in.putExtra("is_registered", true); // call next Activity --> next screen comes up startActivity(in);
但是我们可以以一种更加直接的方式,使用Parcelable 类在组件之间传递实体对象,例如:
In the first Activity:
// in CollectDataActivity, populate the Parcelable User object using its setter methods User usr = new User(); usr.setId(id); // collected from user input// etc.. // pass it to another component Intent in = new Intent(this, ProcessDataActivity.class); in.putExtra("user", usr); startActivity(in);
In the second Activity:
// in ProcessDataActivity retrieve User Intent intent = getIntent(); User usr = (User) intent.getParcelableExtra("user");
要达到这样的目的,我们只需要User类实现Parcelable
接口
1 使User类实现Parcelable
接口
2 实现describeContents方法
3 实现抽象方法writeToParcel,该方法将User实体写入Parcel
4 创建静态CREATOR方法,实现Parcelable.Creator接口
5 添加一个构造函数,将Pracel转换为User对象,读取的顺序和writeToParcel方法中写入的顺序一致
import android.os.Parcel; import android.os.Parcelable; public class User implements Parcelable { private long id; private int age; private String phone; private boolean registered; // No-arg Ctor public User(){} // all getters and setters go here //... /** Used to give additional hints on how to process the received parcel.*/ @Override public int describeContents() { // ignore for now return 0; } @Override public void writeToParcel(Parcel pc, int flags) { pc.writeLong(id); pc.writeInt(age); pc.writeString(phone); pc.writeInt( registered ? 1 :0 ); } /** Static field used to regenerate object, individually or as arrays */ public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel pc) { return new User(pc); } public User[] newArray(int size) { return new User[size]; } }; /**Ctor from Parcel, reads back fields IN THE ORDER they were written */ public User(Parcel pc){ id = pc.readLong(); age = pc.readInt(); phone = pc.readString(); registered = ( pc.readInt() == 1 ); } }
不要使用Pcarcel传递图片信息,更加高效的方式传递图片的URI或者Resource ID。
另外Pcarcel不能用于序列化存储,它是一种高效的传输方式,但是不能取代传统的序列化存储机制