英文:
How to use OnSharedPreferenceChangeListener in Kotlin?
问题
我有一个Activity,其中包含一个可变的数字,以及一个(InputMethodService)服务类,该类从Activity中获取一个数字。
我想要的是,当我在Activity中更改可变数字时,能够在服务类中反映出来。
因此,我编写了以下代码,但它没有起作用。是否有错误或错误的代码?
class Activity : AppCompatActivity() {
override fun onCreate() {
var customNumber: Int = 100
val myPreference = getSharedPreferences("number", Context.MODE_PRIVATE)
myPreference.edit().putInt("changeNumber", customNumber).apply()
}
}
在服务中(从Activity获取数字):
class myService : InputMethodService(), SharedPreferences.OnSharedPreferenceChangeListener {
var changedNumber: Int = 0
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
changedNumber = sharedPreferences!!.getInt("changeNumber", 0)
}
}
英文:
I have a Activity that has variable number and a (InputMethodService) Service class that gets a number from the activity.
What I want is that when I change variable number in activity, that reflects on service class.
So I wrote the code like this, but It didn't work. Is there a mistake or wrong code?
class Activity : AppCompatActivity() {
override fun onCreate() {
var customNumber: Int = 100
val myPreference = getSharedPreference("number", Context.MODE_PRIVATE)
myPreference.edit().putInt("changeNumber", customNumber).apply()
}
}
in Service ( get number from activity )
class myService : InputMethodService(), SharedPreferences.OnSharedPreferenceChangeListener {
var changedNumber: Int = 0
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
changedNumber = sharedPrefrences!!.getInt("changeNumber", 0)
}
}
答案1
得分: 0
看起来你忘记了注册/注销监听器:
https://stackoverflow.com/a/3799894/7434090
英文:
It looks like you're forgetting to register/unregister the listener:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论