话不多说,直接上代码:
/**
* SP工具类
* */
class SharedPreferenceUtil private constructor(context: Context) {
private val preferences: SharedPreferences by lazy {
context.getSharedPreferences(fileName?: DEFAULT_FILE_NAME, Context.MODE_PRIVATE)
}
private val editor: SharedPreferences.Editor by lazy { preferences.edit() }
companion object {
private const val DEFAULT_FILE_NAME = "coin_prefs"
private var instance: SharedPreferenceUtil? = null
private var fileName: String? = null
@Synchronized
fun getInstance(context: Context): SharedPreferenceUtil? {
if (instance == null) {
instance = SharedPreferenceUtil(context)
}
return instance
}
@Synchronized
fun getInstance(context: Context, customFileName: String): SharedPreferenceUtil? {
fileName = customFileName
if (instance == null) {
instance = SharedPreferenceUtil(context)
}
return instance
}
}
fun putString(key: String, value: String) {
editor.putString(key, value).apply()
}
fun putBoolean(key: String, value: Boolean) {
editor.putBoolean(key, value).apply()
}
fun putFloat(key: String, value: Float) {
editor.putFloat(key, value).apply()
}
fun putInt(key: String, value: Int) {
editor.putInt(key, value).apply()
}
fun putLong(key: String, value: Long) {
editor.putLong(key, value).apply()
}
fun clear() {
editor.clear().apply()
}
fun remove(key: String) {
editor.remove(key).apply()
}
fun getString(key: String, defValue: String): String? {
return preferences.getString(key, defValue)
}
fun getBoolean(key: String, defValue: Boolean): Boolean {
return preferences.getBoolean(key, defValue)
}
fun getFloat(key: String, defValue: Float): Float {
return preferences.getFloat(key, defValue)
}
fun getInt(key: String, defValue: Int): Int {
return preferences.getInt(key, defValue)
}
fun getLong(key: String, defValue: Long): Long {
return preferences.getLong(key, defValue)
}
fun contains(key: String): Boolean {
return preferences.contains(key)
}
}
小tips:如果数据读写不频繁,例如在冷启动阶段读一下开关配置等,完全可以用sp,但是读写频繁,或者数据量大,建议还是找一下更优解,毕竟SharedPreferences的底层实现为读写XML文件,并且每次读写都会创建一个新的Editor,这就使得其加载文件和解析文件的性能损耗巨大,另外跨进程也不是它的强项。