打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Android序列化
序列化原因
序列化的原因基本可以归纳为以下三种情况:
1.永久性保存对象,保存对象的字节序列到本地文件中;
2.对象在网络中传递;
3.对象在IPC间传递。
序列化方法
在Android系统中关于序列化的方法一般有两种,分别是实现Serializable接口和Parcelable接口,其中Serializable接口是来自Java中的序列化接口,而Parcelable是Android自带的序列化接口。
上述的两种序列化接口都有各自不同的优缺点,我们在实际使用时需根据不同情况而定。
1.Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC,而相比之下Parcelable的性能更高(毕竟是Android自带的),所以当在使用内存时(如:序列化对象在网络中传递对象或序列化在进程间传递对象),更推荐使用Parcelable接口。
2.但Parcelable有个明显的缺点:不能能使用在要将数据存储在磁盘上的情况(如:永久性保存对象,保存对象的字节序列到本地文件中),因为Parcel本质上为了更好的实现对象在IPC间传递,并不是一个通用的序列化机制,当改变任何Parcel中数据的底层实现都可能导致之前的数据不可读取,所以此时还是建议使用Serializable 。
代码实现
Serializable的接口实现很简单,只需让需要序列化的类继承Serializable 即可,系统会自动将其序列化,
Parcelable接口的实现及使用
android提供了一种新的类型:parcel(英文解释:包裹,小包),本类用来封装数据的容器,封装后的数据可以通过Intent或IPC传递,除了基本类型外,只有实现了Parcelable接口的类才能放入parcel中。实现Parcelable接口主要可以分为一下几步:
1)implements Parcelable。
2)重写writeToParcel方法,将你的对象序列化为一个Parcel对象,即:将类的数据写入外部提供的Parcel中,打包需要传递的数据到Parcel容器保存,以便从Parcel容器获取数据。
3)重写describeContents方法,内容接口描述,默认返回0即可。
4)实例化静态内部对象CREATOR实现接口Parcelable.Creator 。
注意:若将Parcel看成是一个流,则先通过writeToParcel把对象写到流里面,再通过createFromParcel从流里读取对象,因此类实现的写入顺序和读出顺序必须一致。
Parcelable的实现使用:
Parcelabel 的实现,需要在类中添加一个静态成员变量 CREATOR,这个变量需要继承 Parcelable.Creator 接口。
[java] view plaincopy
package com.zlc.provider;
import android.os.Parcel;
import android.os.Parcelable;
public class Students implements Parcelable{
private int stu_id;
private String stu_name;
public Students(Parcel source){
stu_id = source.readInt();
stu_name = source.readString();
}
public int getStu_id() {
return stu_id;
}
public void setStu_id(int stu_id) {
this.stu_id = stu_id;
}
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeInt(stu_id);
dest.writeString(stu_name);
}
//Interface that must be implemented and provided as a public CREATOR field that generates instances of your Parcelable class from a Parcel.
public final static Parcelable.Creator<Students> CREATOR = new Parcelable.Creator<Students>() {
@Override
public Students createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Students(source);
}
@Override
public Students[] newArray(int size) {
// TODO Auto-generated method stub
return new Students[size];
}
};
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android中的序列化机制
Android 使用Parcelable序列化对象
简述:Android中Parcelable接口
[android] Serializable 和 Parcelable 区别
Android序列化问题与思考
Serializable & Parcelable接口总结和区别
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服