Android IPC---Parcelable接口(Android用它比较多,用来传递类的对象)

Parcelable接口是Android提供的,一般用它的次数比较多,用来传递类的对象。

此接口实现序列化后可以通过Inten和Binder传递。

public class User implements Parcelable{
	public int userId;
	public String userName;
	public boolean isMale;
	public Book book;//这里是个对象
	public User(int userId,String userName,boolean isMale){
		//..省略
	}
	
	/**
	 * 功能描述
	 * @return
	 */
	public int describeContents() {
		return 0;
	}
	
	/**
	 * 序列化
	 * @param out
	 * @param flages
	 */
	public void writeToParcel(Parcel out, int flages) {
		out.writeInt(userId);
		out.writeString(userName);
		out.writeInt(isMale ? 1 : 0);//boolean值也是写int
		out.writeParcelable(book, 0);//book对象
	}
	/**
	 * 反序列化
	 */
	public static final Parcelable.Creator<User> CREATOR =
			new Parcelable.Creator<User>() {
		public User createFromParcel(Parcel in) {
			return new User(in);
		}
		public User[] newArray(int size) {
			return new User[size];
		}
	};
	
	private User(Parcel in) {
		userId = in.readInt;
		userName = in.readString();
		isMale = (in.readInt() == 1);
		book = in.readParcelable(Thread.currentThread().getContextClassLoader());
		//book是另一个可序列化对象,所以反序列化需要传递当前线程的上下文类加载器,否则会报无法找到类的错误。
	}
}
系统提供了许多实现了Parcelable接口的类,它们可以直接序列化(Intent,Bundle,Bitmap),List和Map也可以,前提是所有元素都可序列化。

猜你喜欢

转载自blog.csdn.net/fyq520521/article/details/80076576