Android Serializable

   2016-12-01 0
核心提示:Serializable是java提供的标准序列化接口,它是一个空接口,为对象提供标准的序列化和反序列化操作。You can just implement Serializable interface and add override methods.The problem with this approach is that reflection is used and it is a slow

Serializable 是java提供的标准序列化接口,它是一个空接口,为对象提供标准的序列化和反序列化操作。

You can just implement Serializable interface and add override methods.The problem with this approach is that reflection is used and it is a slow process. This method create a lot of temporary objects and cause quite a bit of garbage collection. Serializable interface is easier to implement.

实现接口 Serializable 接口

publicclassMyObjectsimplementsSerializable{

privateString name;
privateintage;

publicArrayList<String> address;

publicMyObjects(String name,intage, ArrayList<String> address){
super();
this.name = name;
this.age = age;
this.address = address;
}

publicArrayList<String>getAddress(){
if(!(address ==null))
returnaddress;
else
returnnewArrayList<String>();
}

publicStringgetName(){
returnname;

}

publicStringgetAge(){
returnage;
}

}

传递 Serializable 对象:

//MyObjects instance
MyObjects mObjects = newMyObjects("name","age","Address array here");

//Passing MyObjects instance via intent
Intent mIntent = newIntent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObjects);
startActivity(mIntent);


//Getting MyObjects instance
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects) mIntent.getSerializableExtra("UniqueKey");

Serializable 的实现原理是将需要序列化的对象写入文件内,反序列化的时候再从文件内读取数据组成对象。这个过程中会有一个 serialVersionID 来标记当前序列化文件的版本,反序列化的时候会

检测当前类的serialVersionID和文件中的serialVersionID是否一样,如果一样,那么就说明当前类和序列化的对象的版本相同(即使类不同,也能恢复大部分数据),否则就说明当前类和序列化对象有所不同,可能是增减了成员变量之类的变化,这个时候反序列化程序就会crash。

另外,序列化和反序列化的过程是通过 writeObjectreadObject 来实现的,可以重写他们改变系统的默认序列化和反序列化过程。

ObjectOutputStream 序列化

//序列化
User user = new User(0,"jack",true);
ObjectOutputStream out = new ObjectOutputStream(
 new FileOutputStream("cache.txt"));
 out.writeObject(user);
 out.close();

ObjectInputStream 反序列化

//反序列化
ObjectInputStream in = newObjectInputStream(
newFileInputStream("cache.txt"));
User user = (User) in.readObject();
in.close();

Parcelable

android中提供的序列化接口,实现这个接口以后就可以实现序列化并且可以通过Intent和Binder传递。

Parcelable process is much faster than serializable. One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it. It also stands to reason that the code has been heavily optimized for this purpose.

//MyObjects Parcelable class

importjava.util.ArrayList;

importandroid.os.Parcel;
importandroid.os.Parcelable;

publicclassMyObjectsimplementsParcelable{

privateintage;
privateString name;

privateArrayList<String> address;

publicMyObjects(String name,intage, ArrayList<String> address){
this.name = name;
this.age = age;
this.address = address;

}

publicMyObjects(Parcel source){
 age = source.readInt();
 name = source.readString();
 address = source.createStringArrayList();
}

@Override
publicintdescribeContents(){
return0;
}

@Override
publicvoidwriteToParcel(Parcel dest,intflags){
 dest.writeInt(age);
 dest.writeString(name);
 dest.writeStringList(address);

}

publicintgetAge(){
returnage;
}

publicStringgetName(){
returnname;
}

publicArrayList<String>getAddress(){
if(!(address ==null))
returnaddress;
else
returnnewArrayList<String>();
}

publicstaticfinalCreator<MyObjects> CREATOR =newCreator<MyObjects>() {
@Override
publicMyObjects[] newArray(intsize) {
returnnewMyObjects[size];
 }

@Override
publicMyObjectscreateFromParcel(Parcel source){
returnnewMyObjects(source);
 }
};

}
MyObjects mObjects = newMyObjects("name","age","Address array here");

//Passing MyOjects instance
Intent mIntent = newIntent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", mObjects);
startActivity(mIntent);

//Getting MyObjects instance
Intent mIntent = getIntent();
MyObjects workorder = (MyObjects) mIntent.getParcelable("UniqueKey");

//You can pass Arraylist of Parceble obect as below

//Array of MyObjects
ArrayList<MyObjects> mUsers;

//Passing MyOjects instance
Intent mIntent = newIntent(FromActivity.this, ToActivity.class);
mIntent.putParcelableArrayListExtra("UniqueKey", mUsers);
startActivity(mIntent);


//Getting MyObjects instance
Intent mIntent = getIntent();
ArrayList<MyObjects> mUsers = mIntent.getParcelableArrayList("UniqueKey");

Parcelable and Serializable 比较

  1. Parcelable is faster than serializable interface
  2. Parcelable interface takes more time for implemetation compared to serializable interface
  3. serializable interface is easier to implement
  4. serializable interface create a lot of temporary objects and cause quite a bit of garbage collection
  5. Parcelable array can be pass via Intent in android

If you want to be a good citizen, take the extra time to implement Parcelable since it will perform 10 times faster and use less resources.

However, in most cases, the slowness of Serializable won’t be noticeable. Feel free to use it but remember that serialization is an expensive operation so keep it to a minimum.

If you are trying to pass a list with thousands of serialized objects, it is possible that the whole process will take more than a second. It can make transitions or rotation from portrait to landscape feel very sluggish.

References

 
标签: 安卓开发
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 安卓中通知功能的具体实现
    安卓中通知功能的具体实现
    通知[Notification]是Android中比较有特色的功能,当某个应用程序希望给用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知实现。使用通知的步骤1、需要一个NotificationManager来获得NotificationManager manager = (NotificationManager
    02-05 安卓开发
  • Android view系统分析-setContentView
    Android view系统分析-setContentView
    第一天上班,列了一下今年要学习的东西。主要就是深入学习Android相关的系统源代码,夯实基础。对于学习Android系统源代码,也没什么大概,就从我们平常使用最基础的东西学起,也就是从view这个切入点开始学习Android的源码,在没分析源码之前,我们有的时候
    02-05 安卓开发
  • 如何进行网络视频截图/获取视频的缩略图
    如何进行网络视频截图/获取视频的缩略图
    小编导读:获取视频的缩略图,截图正在播放的视频某一帧,是在音视频开发中,常遇到的问题。本文是主要用于点播中截图视频,同时还可以获取点播视频的缩略图进行显示,留下一个问题,如下图所示, 如果要获取直播中节目视频缩略图,该怎么做呢?(ps:直播是直
  • Android NDK 层发起 HTTP 请求的问题及解决
    Android NDK 层发起 HTTP 请求的问题及解决
    前言新的一年,大家新年快乐~~鸡年大吉!本次给大家带来何老师的最新文章~虽然何老师还在过节,但依然放心不下广大开发者,在此佳节还未结束之际,给大家带来最新的技术分享~ 事件的起因不说了,总之是需要实现一个 NDK 层的网络请求。为了多端适用,还是选择
  • Android插件化(六): OpenAtlasの改写aapt以防止资源ID冲突
    Android插件化(六): OpenAtlasの改写aapt以防
    引言Android应用程序的编译中,负责资源打包的是aapt,如果不对打包后的资源ID进行控制,就会导致插件中的资源ID冲突。所以,我们需要改写aapt的源码,以达到通过某种方式传递资源ID的Package ID,通过aapt打包时获取到这个Package ID并且应用才插件资源的命名
    02-05 安卓开发
  • Android架构(一)MVP架构在Android中的实践
    Android架构(一)MVP架构在Android中的实践
    为什么要重视程序的架构设计 对程序进行架构设计的原因,归根结底是为了 提高生产力 。通过设计是程序模块化,做到模块内部的 高聚合 和模块之间的 低耦合 (如依赖注入就是低耦合的集中体现)。 这样做的好处是使得程序开发过程中,开发人员主需要专注于一点,
    02-05 安卓开发
  • 安卓逆向系列教程 4.2 分析锁机软件
    安卓逆向系列教程 4.2 分析锁机软件
    安卓逆向系列教程 4.2 分析锁机软件 作者: 飞龙 这个教程中我们要分析一个锁机软件。像这种软件都比较简单,完全可以顺着入口看下去,但我这里还是用关键点来定位。首先这个软件的截图是这样,进入这个界面之后,除非退出模拟器,否则没办法回到桌面。上面那
    02-05 安卓开发
  • Android插件化(二):OpenAtlas插件安装过程分析
    Android插件化(二):OpenAtlas插件安装过程分析
    在前一篇博客 Android插件化(一):OpenAtlas架构以及实现原理概要 中,我们对应Android插件化存在的问题,实现原理,以及目前的实现方案进行了简单的叙述。从这篇开始,我们要深入到OpenAtlas的源码中进行插件安装过程的分析。 插件的安装分为3种:宿主启动时立
    02-05 安卓开发
  • [译] Android API 指南
    [译] Android API 指南
    众所周知,Android开发者有中文网站了,API 指南一眼看去最左侧的菜单都是中文,然而点进去内容还是很多是英文,并没有全部翻译,我这里整理了API 指南的目录,便于查看,如果之前还没有通读,现在可以好好看一遍。注意,如果标题带有英文,说明官方还没有翻
  • 使用FileProvider解决file:// URI引起的FileUriExposedException
    使用FileProvider解决file:// URI引起的FileUri
    问题以下是一段简单的代码,它调用系统的相机app来拍摄照片:void takePhoto(String cameraPhotoPath) {File cameraPhoto = new File(cameraPhotoPath);Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);takePhotoIntent.putExtra(Medi
    02-05 安卓开发
点击排行