1

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)
    }
}
EPISODE
  • 37
  • 4

1 Answers1

0

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

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

Gavin Wright
  • 3,124
  • 3
  • 14
  • 35
  • Thanks, but I have more question, I'd like to get number in a service ( inputmethodservice ), not in a activity. Service component have no onPause(), onResume() method. Then how to register/unregister the listner? Can onStartInputView(), onDestroy() do it? – EPISODE Aug 27 '20 at 06:42
  • I would think `onCreate()` and `onDestroy()` would be best. – Gavin Wright Aug 27 '20 at 06:58