用MMKV代替SharedPreferences存储键值对数据

 介绍:

MMKV——基于 mmap 的高性能通用 key-value 组件

上速度性能对比图:

 


使用三步走:

1、依赖:

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

2、初始化(在入口处):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String rootDir = MMKV.initialize(this);
    System.out.println("mmkv root: " + rootDir);
    //……
}

3、使用:

import com.tencent.mmkv.MMKV;
    
MMKV kv = MMKV.defaultMMKV();

kv.encode("bool", true);
boolean bValue = kv.decodeBool("bool");

kv.encode("int", Integer.MIN_VALUE);
int iValue = kv.decodeInt("int");

kv.encode("string", "Hello from mmkv");
String str = kv.decodeString("string");

完。

附上官方GitHub地址:

经验分享 程序员 微信小程序 职场和发展