Aarcelable 是Android提供的序列化接口,缺点是使用起来有点麻烦,优点是效率高,也是Android推荐的序列化方式。
序列化代码 :
public class User implements Parcelable { private int userId; private String userName; private boolean isMale; private Book book; protected User(Parcel in) { in.writeInt(userId); in.writeString(userName);
in.writeInt(isMale?1:0); in.writeParcelable(book,0); } public static final Creator<User> CREATOR = new Creator<User>() { @Override public User createFromParcel(Parcel in) { return new User(in); } @Override public User[] newArray(int size) { return new User[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { userId = dest.readInt(); userName = dest.readString(); isMale = dest.readInt()==1; /** * 当序列化属性为一个可序列化对象时 反序列化过程需要传递当前线程的上下文类加载器 */ book = dest.readParcelable(Thread.currentThread().getContextClassLoader()); } }需要注意的是使用Parcelable序列化 对于 boolean类型和可序列化对象的操作。