Reputation: 338
I have an application that consists of two separate processes; the main application and a background service that has a separate process defined with android:process=":process_name"
in the manifest.
When using SharedPreferences
I observe that I can store and load values on one process, and retrieve them on the other process completely fine.
Main Activity:
override fun onStart() {
// ...
val prefs = getSharedPreferences(PREFERENCES_ID, Context.MODE_PRIVATE)
val editor = prefs.edit()
editor.putInt("TEST", 42)
editor.commit()
}
Service:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// ...
val prefs = getSharedPreferences(PREFERENCES_ID, Context.MODE_PRIVATE)
val retrieved = prefs.getInt("TEST", -1)
Log.d("Service", "Retrieved $retrieved") // prints "Retrieved 42"
}
However, when registering a OnSharedPreferenceChangeListener
to observe these changes on both the activity and service, I only recieve the changes my SharedPreferences
instance on the process that the change was made on. (This also happens when creating the shared preferences instance with the Activity/Service's applicationContext
.)
I also note that this behaviour does not occur when removing the android:process
directive in the manifest, which leads me to believe the different processes cause this behaviour.
(I acknowledge I could move my application to be a single process or implement a "changed" message of some sort through some other IPC such as a Messenger
every time my code makes a change to the SharedPreferences
, however these are not attractive options for this application.)
Upvotes: 1
Views: 103