Android持久化数据存储就像访问Static变量一样简单,可完全取代SharedPreferences的存储功能。支持List<*>、Map<*,*>、String、Int、Long、Float、Double和Java Been等。
使用步骤
使用步骤极其简单,只需要定义好字段名称及类型便可使用。
定义举例
inline val mDataStoreConfigs: DataStoreConfig get() = DataStoreConfig.instance
class DataStoreConfig {
//定义一个默认值为""的字段 -- name
var name by property("")
companion object {
val instance by lazy { return@lazy DataStoreConfig() }
}
}
使用举例
//存储
mDataStoreConfigs.name = "Zhang San"
//读取
textview.text = mDataStoreConfigs.name
其他类型数据举例
//定义一个默认值为false的Boolean字段 -- expBoolean
var expBoolean by property(false)
//定义一个默认值为0的Int字段 -- expInt
var expInt by property(0)
//定义一个默认值为0的Long字段 -- expLong
var expLong by property(0L)
//定义一个默认值为0的Float字段 -- expFloat
var expFloat by property(0.0f)
//定义一个默认值为0的Double字段 -- expDouble
var expDouble by property(0.0)
//定义一个默认值为[0, 1, 2, 3, 4, 5]的byte[]数组字段 -- expBytes
var expBytes by property(byteArrayOf(0, 1, 2, 3, 4, 5))
//定义一个默认值为Java been -- ExpBeen字段 -- expBeen
var expBeen by property(ExpBeen())
//定义一个默认值为空的Map字段 -- expMap
var expMap by jsonProperty(object : TypeReference<Map<String, ExpBeen>>() {},mutableMapOf())
//定义一个默认值为空的List字段 -- expList
var expList by jsonProperty(object : TypeReference<MutableList<ExpBeen>>() {},mutableListOf())
底层实现
目前持久化存储采用的是微信的MMKV,拥有不错的稳定性及存储性能。什么是MMKV? 点击链接
class MMKVDataStore(name: String) : DataStore {
private var mmkv: MMKV = MMKV.mmkvWithID(name)
override fun clearAll() {
mmkv.clearAll()
}
override fun delete(key: String) {
mmkv.removeValueForKey(key)
}
override fun write(key: String, obj: Any): Boolean {
return if (obj is String) {
mmkv.encode(key, obj)
} else if (obj is Int) {
mmkv.encode(key, obj)
} else if (obj is Boolean) {
mmkv.encode(key, obj)
} else if (obj is Float) {
mmkv.encode(key, obj)
} else if (obj is Long) {
mmkv.encode(key, obj)
} else if (obj is Double) {
mmkv.encode(key, obj)
} else if (obj is ByteArray) {
mmkv.encode(key, obj)
} else if (obj is Parcelable) {
mmkv.encode(key, obj)
} else {
mmkv.encode(key, JSON.toJSONString(obj))
}
}
override fun readString(key: String, def: String?): String? {
return mmkv.decodeString(key, def)
}
override fun readBoolean(key: String, def: Boolean): Boolean {
return mmkv.decodeBool(key, def)
}
override fun readInt(key: String, def: Int): Int {
return mmkv.decodeInt(key, def)
}
override fun readLong(key: String, def: Long): Long {
return mmkv.decodeLong(key, def)
}
override fun readFloat(key: String, def: Float): Float {
return mmkv.decodeFloat(key, def)
}
override fun readDouble(key: String, def: Double): Double {
return mmkv.decodeDouble(key, def)
}
override fun readBytes(key: String, def: ByteArray?): ByteArray? {
return mmkv.decodeBytes(key, def)
}
}
使用远程依赖
在工程根目录的build.gradle中添加
allprojects {
repositories {
maven { url 'https://www.jitpack.io' }
...
}
}
添加依赖
implementation 'com.github.chockqiu:DataStoreProxy:1.1'
网友评论