package com.common.commonlib.utils import com.common.commonlib.log.Logger.e import com.tencent.mmkv.MMKV /** * MMKV的工具类 * * @author wangym * @since 2021-12-14 */ object MMKVUtils { const val TAG = "MMKVUtils" /** * 保存数据 * @param key 键 * @param value 值 * @param args 第一位:自定义保存ID * 第二位:是否支持跨进程 */ fun put(key: String, value: T, vararg args: Any) { val kv: MMKV = getKV(*args) when (value) { is String -> kv.putString(key, value) is Boolean -> kv.putBoolean(key, value) is Int -> kv.putInt(key, value) is Float -> kv.putFloat(key, value) is Long -> kv.putLong(key, value) is ByteArray -> kv.putBytes(key, value) is Set<*> -> kv.putStringSet(key, value as Set) else -> { e(TAG, "got error value type,please check") } } } fun getByteArray(key: String, vararg args: Any): ByteArray? { return getKV(*args).getBytes(key, null) } fun getBoolean(key: String, vararg args: Any): Boolean { return getKV(*args).getBoolean(key, false) } fun getFloat(key: String, vararg args: Any): Float { return getKV(*args).getFloat(key, 0f) } fun getInt(key: String, vararg args: Any): Int { return getKV(*args).getInt(key, 0) } fun getLong(key: String, vararg args: Any): Long { return getKV(*args).getLong(key, 0L) } fun getString(key: String, vararg args: Any): String? { return getKV(*args).getString(key, "") } fun getStringSet(key: String, vararg args: Any): Set? { return getKV(*args).getStringSet(key, null) } private fun getKV(vararg args: Any): MMKV { return when (args.size) { 1 -> MMKV.mmkvWithID(args[0] as String) 2 -> MMKV.mmkvWithID(args[0] as String, MMKV.MULTI_PROCESS_MODE) else -> MMKV.defaultMMKV() } } }