/**
* MMKV 基于 mmap 的高性能通用 key-value 组件工具类
*/
public final class MMKVPreferenceUtil {
private MMKVPreferenceUtil() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 存入支持的数据类型
*
* @param key
* @param object
*/
public static void put(String key, Object object) {
MMKV mmkv = MMKV.defaultMMKV();
if (object instanceof String) {
mmkv.encode(key, (String) object);
} else if (object instanceof Integer) {
mmkv.encode(key, (Integer) object);
} else if (object instanceof Boolean) {
mmkv.encode(key, (Boolean) object);
} else if (object instanceof Float) {
mmkv.encode(key, (Float) object);
} else if (object instanceof Double) {
mmkv.encode(key, (Double) object);
} else if (object instanceof Long) {
mmkv.encode(key, (Long) object);
} else if (object instanceof Parcelable) {
mmkv.encode(key, (Parcelable) object);
} else if (object instanceof Set) {
mmkv.encode(key, (Set<String>) object);
} else {
mmkv.encode(key, (String) object);
}
}
/**
* 获取基本数据类型
*
* @param key
* @param defaultObject
* @return
*/
public static Object get(String key, Object defaultObject) {
MMKV mmkv = MMKV.defaultMMKV();
if (defaultObject instanceof String) {
return mmkv.decodeString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return mmkv.decodeInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return mmkv.decodeBool(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return mmkv.decodeFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return mmkv.decodeLong(key, (Long) defaultObject);
} else if (defaultObject instanceof Double) {
return mmkv.decodeDouble(key, (Double) defaultObject);
} else if (defaultObject instanceof Byte) {
return mmkv.decodeBytes(key);
} else if (defaultObject instanceof Set) {
return mmkv.decodeStringSet(key, (Set) defaultObject);
}
return null;
}
/**
* 获取对象
*
* @param key
* @param tClass
* @param <T>
* @return
*/
public static <T extends Parcelable> T getObject(String key, Class<T> tClass) {
MMKV mmkv = MMKV.defaultMMKV();
return mmkv.decodeParcelable(key, tClass, null);
}
/**
* 删除某个键值对
*
* @param key
*/
public static void remove(String key) {
MMKV mmkv = MMKV.defaultMMKV();
mmkv.removeValueForKey(key);
}
/**
* 清除所有
*/
public static void clearAll() {
MMKV mmkv = MMKV.defaultMMKV();
mmkv.clearAll();
}
/**
* 查询某个key是否已经存在
*/
public static boolean contains(String key) {
MMKV mmkv = MMKV.defaultMMKV();
return mmkv.containsKey(key);
}
}
Android MMKV数据持久化存储
最新推荐文章于 2024-06-05 23:52:04 发布