微信官方轻量级键值对存储框架MMKV
GitHub:https://github.com/Tencent/MMKV
Android 文档:https://github.com/Tencent/MMKV/wiki/android_tutorial
MMKV与SharedPreferences性能对比:
初始化MMKV
在APP启动时初始化MMKV
@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有一个默认全局实例,可以直接使用
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
删除及查询
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实例
MMKV mmkv = MMKV.mmkvWithID("user");
mmkv.encode("user_id", 100);
Log.i("yezhou", "UserId: " + mmkv.decodeInt("user_id"));
如果需要支持多进程访问,可以在MMKV初始化时设置 MMKV.MULTI_PROCESS_MODE
MMKV mmkv = MMKV.mmkvWithID("share", MMKV.MULTI_PROCESS_MODE);
mmkv.encode("bool", true);
支持数据类型
基本类型:
boolean、int、long、float、double、byte[]
类及集合:
String、Set<String>
从SharedPreferences迁移
参考:https://github.com/Tencent/MMKV/wiki/android_tutorial#migrating-from-sharedpreferences
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/18/wechat-official-lightweight-key-value-pair-storage-framework-mmkv/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
共有 0 条评论