gpt4 book ai didi

Android - SharedPreferences - 上下文

转载 作者:太空狗 更新时间:2023-10-29 15:50:21 25 4
gpt4 key购买 nike

我想使用 kotlin 在 android 中为我的 SharedPreference 创建一个帮助程序类。不幸的是,我需要 Context 并且我不想在每次调用首选项时都将其设置为参数。

如果我为上下文使用伴随对象并在应用程序启动时设置它,我会收到以下错误:不要将 Android 上下文类放在静态字段中;这是内存泄漏(并且还会破坏 Instant Run)

那么如何在每次调用首选项时获取上下文而不传递它呢?

 var isWorking: Boolean
get() = getBoolean(IS_WORKING)
set(isWorking) = setPreference(IS_WORKING, isWorking)

private fun setPreference(key: String, value: Boolean) {
val editor = settings.edit()
editor.putBoolean(key, value)
editor.commit()
}

private val settings: SharedPreferences by lazy {
context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
}

最佳答案

考虑使用对象而不是类。它只有一个实例,并且 SharedPreferences 可以使用应用程序的上下文进行初始化,如下所示:

object AppPreferences {
private const val NAME = "SpinKotlin"
private const val MODE = Context.MODE_PRIVATE
private lateinit var preferences: SharedPreferences
// list of app specific preferences
private val IS_FIRST_RUN_PREF = Pair("is_first_run", false)

fun init(context: Context) {
preferences = context.getSharedPreferences(NAME, MODE)
}

/**
* SharedPreferences extension function, so we won't need to call edit()
and apply()
* ourselves on every SharedPreferences operation.
*/
private inline fun SharedPreferences.edit(operation:
(SharedPreferences.Editor) -> Unit) {
val editor = edit()
operation(editor)
editor.apply()
}

var firstRun: Boolean
// custom getter to get a preference of a desired type, with a predefined default value
get() = preferences.getBoolean(IS_FIRST_RUN_PREF.first, IS_FIRST_RUN_PREF.second)

// custom setter to save a preference back to preferences file
set(value) = preferences.edit {
it.putBoolean(IS_FIRST_RUN_PREF.first, value)
}
}

在应用类中:

class SpInKotlinApp : Application() {
override fun onCreate() {
super.onCreate()
AppPreferences.init(this)
}
}

并且由于使用自定义的 get() 和 set() 方法简化了对属性的读写,因此赋值非常容易:

if (!AppPreferences.firstRun) {
AppPreferences.firstRun = true
Log.d("SpinKotlin", "The value of our pref is: ${AppPreferences.firstRun}")
}

查看完整解释here .

关于Android - SharedPreferences - 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47828379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com