Android微信MMKV使用记录

2023-04-11 12:06:26

MMKV 是基于 mmap 内存映射的 key-value 组件,底层序列化/反序列化使用 protobuf 实现,性能高,稳定性强。当然我这等菜鸟是不太理解的,先把用法get再说。

1.依赖注入

dependencies {
    implementation 'com.tencent:mmkv:1.0.10'
    // replace "1.0.10" with any available version
}

2.初始化

在Application处初始化

 MMKV.initialize(this);

3.数据操作

默认使用单进程模式

MMKV kv = MMKV.defaultMMKV();
kv.encode("boolean", true);
boolean bValue = kv.decodeBool("boolean");
kv.encode("int", Integer.MIN_VALUE);
int iValue = kv.decodeInt("int");
kv.encode("string", "Hello from mmkv");
String str = kv.decodeString("string");

如需切到多进程模式可使用MULTI_PROCESS_MODE;
如果要使用多进程且用匿名内存,则使用MMKV.mmkvWithAshmemID(Context context, String mmapID, int size, int mode, String cryptKey)。
后面这些我没试过,有兴趣的可以自己尝试一下,我之前也写过一个关于SharedPreferences 的,相比起来确实是MMKV更加简单好用一些。
对于SharedPreferences ,MMKV 提供了 importFromSharedPreferences() 函数,可以比较方便地迁移数据过来,还额外实现了一遍 SharedPreferences、SharedPreferences.Editor 这两个 interface,在迁移的时候只需两三行代码即可,其他 CRUD 操作代码都不用改。

  • 作者:SinMin_G
  • 原文链接:https://blog.csdn.net/qq_36487432/article/details/82877889
    更新时间:2023-04-11 12:06:26