萌新Android笔记----多线程多进程下的IPC机制

  • 跳过开头
    skip。。。。。。。。rider hensin。。。cast off。。。。clock up。。。。

IPC基础

学习IPC的路上我们不得不接触Serializable接口,Parcelable接口和Binder。Serializable和Parcelable接口可以完成对象的序列化(序列化可以实现在网络,程序间传递对象,永久保存),当我们需要通过Intent和Binder传输数据时就需要Parcelable或Serializable。一一看过去吧

  • Serializable
    这个接口可以简单实现对象的序列化和反序列化,简单操作如下
private static final long seialVersionUID = 111111111111111111L;

这样就能自动实现序列化过程,但这个UID并非必须,UID影响的时反序列化过程,来个具体的

public class User implements Serializable {
	private static final long serialVersionUID = 111111111111111111L;
	public int userId;
	public String userName;
	public boolean isMale;
}
User user = new User(0,"jake",true); //实例化User类
/***序列化过程***/
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("cache.txt"));
out.writeObject(user);
out.close();
/***反序列化过程***/
ObjectInputStream in = new ObjectInputStream(new FileInputStream("cache.txt"));
User newUser = (User)in.readObject();
in.close();

这样就实现通过Serializable方法来实现对象的序列化和反序列化,序列化的核心是writeObject,反序列化的核心是readObject,简单易懂,值得一提的是反序列化后新生成的newUser和user内容完全一致,但两者不是同一个对象。
为啥这里没serialVersionUID呢?之前的一长串1有什么含义呢?萌新如我不经发出疑问。实际上这个serialVersionUID是用来辅助序列化和反序列化过程的。原则上序列化后的数据中的serialVersionUID只有和
当前类的serialVersionUID相同才能正常反序列化。该UID的详细工作机制是序列化时系统会把UID放入一个文件,反序列化时会监测UID,如果和当前类的UID一致,就可以成功反序列化,如果不一致说明当前类和序列化的类相比发生一些变化

  • Parcelable
    这个接口复杂一些,但实现了就可以用一个类实现序列化并可以通过Intent和Binder传递,如下
public class User implements Parcelable{
	public int userId;
	public String userName;
	public boolean isMale;
	public Book book;
	
	public Book book;

	public User(int userId, String userName,boolean isMale){
		this.userId = userId;
		this.userName = userName;
		this.isMale = isMale;
		}
/***describeContents负责内容描述***/
	public int describeContents(){
		return 0;
		}
/***writeToParcel负责序列化***/
	public void writeToParcel(Parcel out, int flags){
		out.writeInt(userId);
		out.writeString(userName);
		out.writeInt(isMale?1:0);
		out.writeParcelable(book, 0);
		}
/***CREATOR负责反序列化***/
	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());
}
}

首先来认识下Parcel,这玩意可以看成运输员,在Binder中传递序列化后的东西。因此在序列化过程中,我们需要通过Parcel的一系列write方法来完成序列化。在反序列化过程中,我们需要通过Parcel的一系列read方法来完成反序列化。

  • 总结
    Serializable使用简单,但因为反复使用I/O操作导致开销大,而Parcelable使用麻烦但效率高。Android推荐的还是Parcelable。萌新今日摸鱼,明天要好好聊聊Binder这一生之敌
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值