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也可以,前提是所有元素都可序列化。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值