Search code examples
androidservicesharedpreferences

Shared Preferences updated value not reflected in Service


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?


Solution

  • As mentioned here

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

    So it wouldn't reflect changes instantaneously.