SharedPreferences in BroadcastReceiver seems to not update?

旧时模样 提交于 2019-11-27 14:45:33

I had the same problem and after struggling for hours to solve it, I finally found the issue causing it. In your AndroidManifest you probably have something like that:

<receiver android:name="AlarmReceiver" android:process=":remote" />

The last attribute (process:remote) cause the receiver to run on a different/new process when it is called. But SharedPreferences is NOT supported between different processes.

So what I did is to remove that last attribute from the manifest. The implication is that the code will now run on the main thread - but if you only have a few lines to show a notification then that shouldn't be a problem. Another way is to call a service to run the long operation.

Unfortunately the solution by Amir Naor not worked in my Android 7 App. It seems that every receiver get always started in a new process.

API < 23

So if your app < API Level 23, you can use the flag Context.MODE_MULTI_PROCESS:

context.getSharedPreferences("mypreferences", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);

API >= 23

What a surprise. Since API Level 23 is the flag Context.MODE_MULTI_PROCESS deprecated and we should use ContentProvider to share the Properties between processes.


There is a very nice library on github: Tray - a SharedPreferences replacement for Android. This library is a ContentProvider wrapper with some other useful features. Give it a try.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!