1

I have a trouble with SharedPreferences when I try read data from remote service.

First, In SplashScreenActivity, my app start and bind my RemoteService

Second, SplashScreenActivity start MainActivity, this MainActivity will save configuration info to SharedPreferences:

SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("ABC_KEY", "abc");
editor.apply();

Then, MainActivity will send Broadcast:

sendBroadcast(new Intent("PLZ_READ_DATA"));

Finally, in RemoteService receive above Broadcast, it will read data from SharedPreferences:

SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String str = mSharedPreferences.getString("ABC_KEY", null);

The problem is str is always null.

What is the magic here? Can anyone explain it and give a solution for read data from SharedPreferences on this case.

Robust
  • 2,415
  • 2
  • 22
  • 37
  • is your remote service running in the same process? what happens if you add logs before and after, can you be sure the insertion happens first? – thepoosh Jul 31 '16 at 17:05
  • `RemoteService` will run in another process. I logged before and after writing data to `SharedPreferences`, everything works exactly, but the read process does not work as expected. – Robust Jul 31 '16 at 17:08

1 Answers1

0

Since you're dealing with multiple processes you need to specify the mode to support that as can be seen from this answer

Community
  • 1
  • 1
thepoosh
  • 12,497
  • 15
  • 73
  • 132
  • Ok, thank you so much. I will try another way, because `MODE_MULTI_PROCESS ` has been deprecated in Android M. – Robust Jul 31 '16 at 17:18