打赏

MMKV学习Android

 implementation 'com.tencent:mmkv-static:1.1.2'

Application

public void onCreate() {
    super.onCreate();

    String rootDir = MMKV.initialize(this);
   
}

CRUD 操作
MMKV 提供一个全局的实例,可以直接使用:

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

kv.encode("bool", true);
System.out.println("bool: " + kv.decodeBool("bool"));

kv.encode("int", Integer.MIN_VALUE);
System.out.println("int: " + kv.decodeInt("int"));

kv.encode("long", Long.MAX_VALUE);
System.out.println("long: " + kv.decodeLong("long"));

kv.encode("float", -3.14f);
System.out.println("float: " + kv.decodeFloat("float"));

kv.encode("double", Double.MIN_VALUE);
System.out.println("double: " + kv.decodeDouble("double"));

kv.encode("string", "Hello from mmkv");
System.out.println("string: " + kv.decodeString("string"));

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

可以看到,MMKV 在使用上还是比较简单的。

删除 & 查询:

MMKV kv = MMKV.defaultMMKV();

kv.removeValueForKey("bool");
System.out.println("bool: " + kv.decodeBool("bool"));
    
kv.removeValuesForKeys(new String[]{"int", "long"});
System.out.println("allKeys: " + Arrays.toString(kv.allKeys()));

boolean hasBool = kv.containsKey("bool");
如果不同业务需要区别存储,也可以单独创建自己的实例:

MMKV* mmkv = MMKV.mmkvWithID("MyID");
mmkv.encode("bool", true);


如果业务需要多进程访问,那么在初始化的时候加上标志位
MMKV.MULTI_PROCESS_MODE:

MMKV* mmkv = MMKV.mmkvWithID("InterProcessKV", MMKV.MULTI_PROCESS_MODE);
mmkv.encode("bool", true);


支持的数据类型
支持以下 Java 语言基础类型:

booleanintlongfloatdoublebyte[]

支持以下 Java 类和容器:

String、Set<String>

任何实现了Parcelable的类型
SharedPreferences 迁移
MMKV 提供了 importFromSharedPreferences() 函数,可以比较方便地迁移数据过来。

MMKV 还额外实现了一遍 SharedPreferences、SharedPreferences.Editor 这两个 interface,在迁移的时候只需两三行代码即可,其他 CRUD 操作代码都不用改。

private void testImportSharedPreferences() {
    //SharedPreferences preferences = getSharedPreferences("myData", MODE_PRIVATE);
    MMKV preferences = MMKV.mmkvWithID("myData");
    // 迁移旧数据
    {
        SharedPreferences old_man = getSharedPreferences("myData", MODE_PRIVATE);
        preferences.importFromSharedPreferences(old_man);
        old_man.edit().clear().commit();
    }
    // 跟以前用法一样
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("bool", true);
    editor.putInt("int", Integer.MIN_VALUE);
    editor.putLong("long", Long.MAX_VALUE);
    editor.putFloat("float", -3.14f);
    editor.putString("string", "hello, imported");
    HashSet<String> set = new HashSet<String>();
    set.add("W"); set.add("e"); set.add("C"); set.add("h"); set.add("a"); set.add("t");
    editor.putStringSet("string-set", set);
    // 无需调用 commit()
    //editor.commit();
}

 

posted @ 2021-02-21 22:27  张学涛  阅读(164)  评论(0编辑  收藏  举报