Shared Preferences updated value not reflected in

2019-07-29 16:33发布

问题:

My application is calling a service at app launch.

In the app, I am updating the value of a given key-value pair

SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.shared_preferences_name), MODE_PRIVATE).edit();
    editor.putString("key",value);
    editor.apply();

and I'm trying to fetch it from the service

SharedPreferences preferences = getSharedPreferences(getString(R.string.shared_preferences_name), MODE_PRIVATE);
String key = preferences.getString("key",null);

but the service always displays the old key value. i.e, the value is reflected only after an app launch or service restart.

How to fetch the updated value in the service without restarting the service or the app?

As mentioned here Shared Preferences don't work across multiple processes. Any alternatives?

回答1:

You need OnSharedPeferencesChangeListener to listen for updates of preferences. Reason it's displaying old value is because it's not updated(Lines of the codes are not called). You need to trigger event to update it.

SharedPreferences prefs = 
PreferenceManager.getDefaultSharedPreferences(this);

prefs.registerOnSharedPreferenceChangeListener(
new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(
        SharedPreferences prefs, String key) {

        String key = prefs.getString("key",null);
    }
});`

EDIT: You need strong reference for SharedPreferences.OnSharedPreferenceChangeListener object. Example here



回答2:

As mentioned here

Note: This class does not support use across multiple processes.

So it wouldn't reflect changes instantaneously.