Android使用Parcelable序列化复杂数据结构

Android序列化方案Parcelable,相比Serializable更快,效率更高,占用内存更少。

Boolean类型

1
2
3
4
5
//write
dest.writeByte((byte) (isDefault ? 1: 0));

//read
isDefault = source.readByte() != 0;

List类型

1
2
3
4
5
6
7
//write
dest.writeList(list);

//read
list = source.readArrayList(String.class.getClassLoader());
list = source.readArrayList(Integer.class.getClassLoader());
list = source.readArrayList(MyEntity.class.getClassLoader());

Map类型

1
2
3
4
5
//write
dest.writeMap(map);

//read
map = source.readHashMap(HashMap.class.getClassLoader());

Array数组

1
2
3
4
5
6
7
8
9
10
11
12
//write
if (array != null) {
dest.writeInt(array.length);
} else {
dest.writeInt(0);
}
dest.writeStringArray(array);

//read
int length = source.readInt();
array = new String[length];
source.readStringArray(array);

实体类

1
2
3
4
5
6
7
8
9
10
11
//如果实体类实现Serializable接口
//write
dest.writeSerializable(entity);
//read
source.readSerializable();

//如果实体类实现Parcelable接口
//write
dest.writeParcelable(entity, flags);
//read
source.readParcelable(MyEntity.class.getClassLoader());

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :