This question has already been answered:

There is a service, there are activations, everyone has SharedPreferences :

Activity:

 public class MainActivity extends AppCompatActivity { SharedPreferences sPref; SharedPreferences.Editor sPrefEdit; final String SAVED_TEXT = "saved_text"; ... @Override protected void onCreate(Bundle savedInstanceState) { sPref = getSharedPreferences(SAVED_TEXT,MODE_PRIVATE); sPrefEdit = sPref.edit(); ... 

and service:

 public class HealthService extends Service { SharedPreferences sPref; SharedPreferences.Editor sPrefEdit; final String SAVED_TEXT = "saved_text"; ... @Override public void onCreate() { sPref = getSharedPreferences(SAVED_TEXT,MODE_PRIVATE); sPrefEdit = sPref.edit(); 

They have the same file preferences, but if the service writes something to the preferences, it sees the activation changes only after the application is restarted, and the service also sees the changes in preferences made by the activations only after the restart.

How to deal with it?

Reported as a duplicate by pavlofff android Nov. 17 '16 at 3:20 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    This is the current feature of SharedPreferences .

    In some cases, you can get the current SharedPreferences state SharedPreferences calling the getSharedPreferences(...) method 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 .

      Try using Dagger to transfer the SharedPreferences object between parts of your application. To get started with Dagger, you need some training for your application. This is written in detail here .

      You will need to create a class module:

       @Module public class AppModule { private final App app; public AppModule(App app) { this.app = app; } @Provides @Singleton SharedPreferences provideSharedPreferences() { return app.getSharedPreferences("settings", 0); } @Provides @Singleton App provideApplication() { return app; } } 

      To access the SharedPreferences object, you will need to add the following line to your Activity and HealthService as a class field:

        @Inject SharedPreferences pref; 

      and perform all actions with settings through this field.