如何在Kotlin中使用OnSharedPreferenceChangeListener?

huangapple go评论96阅读模式
英文:

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:

https://stackoverflow.com/a/3799894/7434090

huangapple
  • 本文由 发表于 2020年8月27日 14:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63610172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定