注入依赖
implementation 'com.tencent:mmkv:1.0.18'
初始化MMKV
String dir = context.getFilesDir().getAbsolutePath() + "/mmkv";
String rootDir = MMKV.initialize(dir);
获得MMKV的实例
MMKV mmkv = 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");
工具类
public class Mmkv {
private static volatile Mmkv instane = null;
private static MMKV mmkv;
public static Mmkv getInstance() {
if (instane == null) {
synchronized (Mmkv.class) {
if (instane == null) {
instane = new Mmkv();
}
}
}
return instane;
}
public void init(Context context) {
String dir = context.getFilesDir().getAbsolutePath() + "/mmkv";
String rootDir = MMKV.initialize(dir);
Log.e("MMKV", "mmkv root: " + rootDir);
mmkv = MMKV.defaultMMKV();
}
/**
* 写入字符串型数据
*/
public static void setString(String key, String value) {
if (mmkv != null) {
mmkv.encode(key, value);
}
}
/**
* 获取字符串型数据
*/
public static String getString(String key) {
if(mmkv != null){
return mmkv.decodeString(key);
}
return null;
}
/**
* 写入整型数据
*/
public static void setInteger(String key, int value) {
if (mmkv != null) {
mmkv.encode(key, value);
}
}
/**
* 获取整型数据
*/
public static Integer getInteger(String key) {
if(mmkv != null){
return mmkv.decodeInt(key,-1);
}
return -1;
}
/**
* 写入布尔型数据
*/
public static void setBoolean(String key, boolean value) {
if (mmkv != null) {
mmkv.encode(key, value);
}
}
/**
* 获取布尔型数据
*/
public static boolean getBoolean(String key) {
if(mmkv != null){
return mmkv.decodeBool(key,false);
}
return false;
}
/**
* 写入长整型数据
*/
public static void setLong(String key, long value) {
if (mmkv != null) {
mmkv.encode(key, value);
}
}
/**
* 获取长整型数据
*/
public static long getLong(String key) {
if(mmkv != null){
return mmkv.decodeLong(key,-1);
}
return -1;
}
public static boolean contains(String key) {
if(mmkv != null){
return mmkv.contains(key);
}
return false;
}
}