I want to update a remote service when the SharedPreferences change. The following used to work with API level 8 (Android 2.2).
My activity has an OnPreferencesChangedListener
which calls the remote service via the service binder object. The interface to the remote service offers a methods prefsChanged(void)
which is called by the listener. Afterwards the interface methods computes among other things the new time for an alert to trigger some action.
This time is also saved to the SharedPreferences
and a broadcast is send. The broadcast is received by my activity which can now display the new alert time.
Activity and remote service get the SharedPreferences
object through a call to a static method GetPrefs(Context)
which answers PreferenceManager.getDefaultSharedPreferences(Context)
.
With API level 15 (Android 4.0.3) this stopped working. Debugging shows that the remote service sees some other version of the SharedPreferences holding different (older?) values. Logging the SharedPreferencesImpl object displays different addresses when logging from the activity and from the remote service. The file system reveals only one shared preferences file.
Is this a bug or did my code work with API level 8 by coincidence?
Any suggestions will be appreciated.
The answer is here, thx to x90: https://stackoverflow.com/a/8723589/1127492
Use MODE_MULTI_PROCESS This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targetting such releases. For applications targetting SDK versions greater than Android 2.3, this flag must be explicitly set if desired.
I would look up here: http://developer.android.com/sdk/api_diff/15/changes.html
and go through the changed packages you have used in your application.
I have encountered the same issue when I upgrade my app from Froyo to ICS. According to the source code of Context.getSharedPreferences from ICS, The solution should be Context.MODE_MULTI_PROCESS
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
SharedPreferencesImpl sp;
synchronized (sSharedPrefs) {
sp = sSharedPrefs.get(name);
if (sp == null) {
File prefsFile = getSharedPrefsFile(name);
sp = new SharedPreferencesImpl(prefsFile, mode);
sSharedPrefs.put(name, sp);
return sp;
}
}
if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
// If somebody else (some other process) changed the prefs
// file behind our back, we reload it. This has been the
// historical (if undocumented) behavior.
sp.startReloadIfChangedUnexpectedly();
}
return sp;
}