微信官方轻量级键值对存储框架MMKV

GitHub:https://github.com/Tencent/MMKV
Android 文档:https://github.com/Tencent/MMKV/wiki/android_tutorial

MMKV与SharedPreferences性能对比:

MMKV与SharedPreferences性能对比

初始化MMKV

在APP启动时初始化MMKV

1
2
3
4
5
6
7
8
9
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String rootDir = MMKV.initialize(this);
Log.i("yezhou", "mmkv root: " + rootDir);
// mmkv root: /data/user/0/cn.appblog.mmkv/files/mmkv
}

基本使用

MMKV有一个默认全局实例,可以直接使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
MMKV kv = MMKV.defaultMMKV();

kv.encode("bool", true);
Log.i("yezhou", "bool: " + kv.decodeBool("bool"));

kv.encode("int", Integer.MIN_VALUE);
Log.i("yezhou", "int: " + kv.decodeInt("int"));

kv.encode("long", Long.MAX_VALUE);
Log.i("yezhou", "long: " + kv.decodeLong("long"));

kv.encode("float", -3.14f);
Log.i("yezhou", "float: " + kv.decodeFloat("float"));

kv.encode("double", Double.MIN_VALUE);
Log.i("yezhou", "double: " + kv.decodeDouble("double"));

kv.encode("string", "Hello from mmkv");
Log.i("yezhou", "string: " + kv.decodeString("string"));

byte[] bytes = {'m', 'm', 'k', 'v'};
kv.encode("bytes", bytes);
Log.i("yezhou", "bytes: " + new String(kv.decodeBytes("bytes")));

// bool: true
// int: -2147483648
// long: 9223372036854775807
// float: -3.14
// double: 4.9E-324
// string: Hello from mmkv
// bytes: mmkv

删除及查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MMKV kv = MMKV.defaultMMKV();

// 删除Key及查询Key默认值
kv.removeValueForKey("bool");
Log.i("yezhou", "bool: " + kv.decodeBool("bool"));

// 查询所有Key
kv.removeValuesForKeys(new String[]{"int", "long"});
Log.i("yezhou", "allKeys: " + Arrays.toString(kv.allKeys()));

// 是否包含Key
boolean hasBool = kv.containsKey("bool");
Log.i("yezhou", "hasBool: " + hasBool);

// bool: false
// allKeys: [string, float, bytes, double]
// hasBool: false

独立存储

如果不同的模块/逻辑需要独立存储,可以创建独立的MMKV实例

1
2
3
MMKV mmkv = MMKV.mmkvWithID("user");
mmkv.encode("user_id", 100);
Log.i("yezhou", "UserId: " + mmkv.decodeInt("user_id"));

如果需要支持多进程访问,可以在MMKV初始化时设置 MMKV.MULTI_PROCESS_MODE

1
2
MMKV mmkv = MMKV.mmkvWithID("share", MMKV.MULTI_PROCESS_MODE);
mmkv.encode("bool", true);

支持数据类型

基本类型:

1
booleanintlongfloatdoublebyte[]

类及集合:

1
String、Set<String>

从SharedPreferences迁移

参考:https://github.com/Tencent/MMKV/wiki/android_tutorial#migrating-from-sharedpreferences

Powered by AppBlog.CN     浙ICP备14037229号

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

访客数 : | 访问量 :