MMKV是腾讯开源的一款是基于 mmap 内存映射的 key-value 组件,底层序列化/反序列化使用 protobuf 实现,性能高,稳定性强。我们现在可以用它完全取代SharePreference。
封装完的工具类我们可以像变量一样读取和存储用户的偏好设置,例如:登陆后的token,uid,从而免登陆等
1.添加引用
implementation 'com.tencent:mmkv-static:1.2.10'
2.创建委托类Preference,读取,存储
我们知道要使用委托,类需要有指定参数的getValue方法,可写的还得有setValue方法,这里我们直接实现ReadWriteProperty接口
import com.tencent.mmkv.MMKV
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class Preference<T>(private val key: String, private val default: T):ReadWriteProperty<Any?,T> {
private val mMkv by lazy {
MMKV.defaultMMKV()
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return when(default){
is Long -> mMkv.decodeLong(key,default)
is Int -> mMkv.decodeInt(key,default)
is Double -> mMkv.decodeDouble(key,default)
is Boolean -> mMkv.decodeBool(key,default)
is Float -> mMkv.decodeFloat(key,default)
is String -> mMkv.decodeString(key,default)
is ByteArray -> mMkv.decodeBytes(key,default)
else -> throw IllegalArgumentException("Unsupported type")
} as T
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
mMkv.let {
when(value){
is String -> it.encode(key, value)
is Float -> it.encode(key, value)
is Boolean -> it.encode(key, value)
is Int -> it.encode(key, value)
is Long -> it.encode(key, value)
is Double -> it.encode(key, value)
is ByteArray -> it.encode(key, value)
is Nothing -> return@let
}
}
}
fun removeKey() = mMkv.removeValueForKey(key)
fun cleanAllMMKV() = mMkv.clearAll()
}
3.SpUtils使用Preference
object SpUtils {
const val KEY_TOKEN = "token"
const val KEY_PHONE = "phone"
const val KEY_USER_ID = "user_id"
var token by Preference(KEY_TOKEN, "")
var phone by Preference(KEY_PHONE, "")
var userId by Preference(KEY_USER_ID, "")
fun removeByKey(key:String){
Preference(key, "").removeKey()
}
fun removeByKey(){
Preference("", "").cleanAllMMKV()
}
}
4.代码使用
保存数据:
SpUtils.phone= "13111113113"
读取数据:
val phone = SpUtils.phone
删除数据:
SpUtils.removeByKey(SpUtils.KEY_PHONE)
|