Preferences基于Kotlin委托实现了SharedPreferences支持多进程、数据加解密、MMKV,另外对原生SharedPreferences进行Hook优化降低ANR,缓存优化。
- 支持多进程
- 支持MMKV无缝接入
- 支持sp和mmkv的getAll方法
- 支持数据加解密(基于androidx.security)
https://github.com/forJrking/Preferences 请start表示对我的支持哦!
- 添加依赖
repositories{... maven{url 'https://jitpack.io' } } dependencies{implementation 'com.github.forjrking.pref:pref-core:2.0.0'// 必须 implementation 'com.github.forjrking.pref:pref-gson:2.0.0'// 非必须 implementation 'com.github.forjrking.pref:pref-ktx:2.0.0'// 非必须 implementation 'com.google.code.gson:gson:2.8.5'//存储对象需要(非必须) implementation 'com.tencent:mmkv-static:1.2.1'// mmkv支持加密和多进程(非必须) implementation 'androidx.security:security-crypto:1.0.0'// sp加密支持(非必须) } // 必须Application 中初始化, 依赖了pref-gson会自动初始化PreferenceHolder.context =this.context // 非必须 如果使用MMKV请初始化并且配置相关MMKV.initialize(this) ... // 非必须 用于序列化对象和集合等数据,sp不建议存大量数据, 依赖了pref-gson会自动初始化PreferenceHolder.serializer =GsonSerializer()- 写一个object类,必须使用kt
object TestSP : PreferencesOwner(){var value:Long by preferenceBinding(0L) var objCase:Game? by preferenceNullableBinding() } // 存入spTestSP.value =100// 读取spval value =TestSP.value println(value) // 0 or 100// getAllTestSP.getAll()?.forEach{Log.d("TAG", "name:${it.key} value:${it.value}") }- 其他api演示
/* * @param name xml名称 默认为实现类类名,为了防止不同类使用相同字段覆盖数据问题 * @param cryptKey 加密密钥 null 表示不用加密 需要api >= 23 * @param isMMKV 是否使用mmkv 默认false * @param isMultiProcess 是否使用多进程 建议mmkv sp性能很差 默认false*/object TestSP : PreferencesOwner("name","cyptKey",isMMKV,isMultiProcess){//带默认值 == getString(key,default) 不可赋值 nullvar testStr:String by preferenceBinding('default') var coin:Long by preferenceBinding(0L) var tes:String? by preferenceNullableBinding() //默认值为 null 可以为其赋值 null//支持所有sp支持的数据类型 以及 object 需要初始化上一步的 GsonSerializervar savedGame:Game? by bindToPreferenceFieldNullable() } //getValue 读取spval str =TestSP.testStr val coin =TestSP.coin println(str) //"" or "something"//setValue 存入spTestSP.testStr ="AX${Random().nextInt(20)}"TestSP.coin =100