序列化及序列化对象传递(Intent/Binder)

1.序列化的两种方式
(1) 实现了Serializable--java自带的序列化接口
(2) 实现Parcelable接口,Android中的序列化接口,效率较高

2.不同序列化接口的具体用法
public class SerializableBean implements Serializable {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ParcelableBean implements Parcelable {
private int age;
private String name;
protected ParcelableBean(Parcel in) {
age = in.readInt();
name = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
}
@Override
public int describeContents() {
// 只有在对象中存在文件描述符时,此方法才返回1
return 0;
}
public static final Creator<ParcelableBean> CREATOR = new Creator<ParcelableBean>() {
@Override
public ParcelableBean createFromParcel(Parcel in) {
return new ParcelableBean(in);
}
@Override
public ParcelableBean[] newArray(int size) {
return new ParcelableBean[size];
}
};
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.使用Intent传递的方式
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
获取方式的不同
(Person) getIntent().getSerializableExtra("person_data");
(Person) getIntent().getParcelableExtra("person_data");

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,463评论 19 139
  • 1.全局获取Context Android提供了一个Application类,每当应用启动的,系统就会自动将这个类...
    figure_ai阅读 3,207评论 0 0
  • 上篇文章介绍了IPC机制的基本概念以及简单使用,文章链接:Android 关于IPC机制的理解(一) 这篇文章主要...
    老实任阅读 4,134评论 0 2
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,760评论 0 17
  • 你渴望将这爱,熔成每一个分子,渗人每一个细胞中。 月明星稀的夜晚 间歇地传来阵阵蝉鸣 明亮的月光透过灰蒙蒙的橱窗 ...
    从前123阅读 1,761评论 0 0