In Activity and Service I create an instance on SharedPreferences like this:

 mSharedPreferences = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE); 

PREFERENCES_NAME is a constant.

However, the problem arises when I try to update the data in them (I enter a line in EditText , I write it down): everything is updated in the Activity , but not in the Service , there is old information left! Moreover, after restarting the Service everything starts working!


I write this (in Activity ):

  SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString(ID_KEY, userIdField.getText().toString()); editor.putString(DOC_URL_KEY, docUrlField.getText().toString()); editor.apply(); 

And I read like this (in Service ):

  mSharedPreferences.getString(DOC_URL_KEY, "") 

Here is the declaration of classes in the manifest:

  <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".DocumentHandleService" android:process="com.dugin.rostislav.reminderofwork.doc_handling_service" /> 

What is the problem, why is this happening and how to fix it?

  • one
    getSharedPreferences(...) with Context.MODE_MULTI_PROCESS flag solve the problem? True it is deprecated . You can read more here . - post_zeew
  • @post_zeew, which is also outdated, which already indicates that its use is incorrect. But, oddly enough, the problem was solved ... - user189127
  • See the answer. - post_zeew

1 answer 1

In some cases, the problem can be solved by calling getSharedPreferences(...) with the Context.MODE_MULTI_PROCESS flag.

But be careful, using Context.MODE_MULTI_PROCESS not recommended , since starting with API level 23 it is deprecated .

This is a constant level in the API level 23. It is not necessary to work on Android. Applications should not attempt to use it. Instead, they should use an explicit cross-process data management approach such as ContentProvider .

The correct solution to the problem is to write your own mechanism, which will be based on the ContentProvider , or you can use something ready, like this .