package com.xw.common.utils import android.annotation.SuppressLint import android.content.Context import com.blankj.utilcode.util.GsonUtils import com.xw.common.utils.LogUtils import com.tencent.mmkv.MMKV class MMKVManager { companion object { val TAG = "MMKVManager" @SuppressLint("StaticFieldLeak") @Volatile private var instance: MMKVManager? = null fun getInstance(): MMKVManager { return instance ?: synchronized(this) { instance ?: MMKVManager().also { instance = it } } } } val isInit: Boolean get() = MMKV.getRootDir() != null val defaultMMKV: MMKV? by lazy { MMKV.defaultMMKV() } /** * 初始化方法 * * 必须先调用一次该方法,才能正常使用其他方法、属性 */ fun init(context: Context) { if (isInit.not()) MMKV.initialize(context) } fun saveString(key: KeyPreferences, value: String) { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) defaultMMKV?.encode(key.value, value) } fun getString(key: KeyPreferences, default: String = ""): String { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) return defaultMMKV?.decodeString(key.value) ?: default } fun saveBoolean(key: KeyPreferences, value: Boolean) { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) defaultMMKV?.encode(key.value, value) } fun getBoolean(key: KeyPreferences, default: Boolean = false): Boolean { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) return defaultMMKV?.decodeBool(key.value, default) ?: default } fun saveModel(key: KeyPreferences, value: T?) { value?.let { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) defaultMMKV?.encode(key.value, GsonUtils.toJson(it)) } } fun deleteModel(key: KeyPreferences) { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) defaultMMKV?.encode(key.value, "") } inline fun getModel(key: KeyPreferences): T? { if (isInit.not()) MMKV.initialize(AppGlobals.getApplication()) val value = defaultMMKV?.decodeString(key.value) return try { GsonUtils.fromJson(value, T::class.java) } catch (e: Exception) { LogUtils.e(TAG, "model e = ${e.message}") null } } fun clear() { defaultMMKV?.clearAll() } } enum class KeyPreferences(val value: String) { TOKEN("token"), USER("user"), THIRD("third"), ACCIDENT("accident"), NEED_READ("needRead"), // 是否需要阅读协议 NEED_UPDATE("needUpdate") // 是否升级 }