简体   繁体   中英

How to use OnSharedPreferenceChangeListener in Kotlin?

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)
    }
}

It looks like you're forgetting to register/unregister the listener:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM