Shared preferences between two processes of the same application

北城余情 提交于 2019-11-27 12:44:48
David Wasser

In Android < 2.3 it works. One process can write changes and the other process can read the changes. The code to read/write shared preferences files (they are actually stored in files) checks if there have been any changes made to the file before reading/writing and they update their cached version accordingly.

In Android > 2.3 it works, but you need to specifically set MODE_MULTI_PROCESS when calling getSharedPreferences().

In Android 2.3 it is broken and it doesn't work :-(

Please note that MODE_MULTI_PROCESS is deprecated in API Level 23 (Android M).

You can check out https://github.com/hamsterksu/MultiprocessPreferences library which provides SharedPreferences-like APIs for accessing SharedPreferences data via a ContentProvider. It also looks like a good alternate after Google removed MODE_MULTI_PROCESS from Android 6.

Sam

No; it isn't safe to do this. The note you quoted is correct. There are known issues that can occur if you try to use SharedPreferences across multiple processes. (See https://code.google.com/p/android/issues/detail?id=66625.)

If you want more proof, take a look at the source code for SharedPreferencesImpl, particularly the parts that save the preferences.

I've worked around this problem by preventing both processes from accessing the SharedPreferences file at the same time. (Here's one way to provide cross-process locking, and here's a complete example implementation I wrote.)

Warning: Unfortunately, MODE_MULTI_PROCESS has been deprecated in Android M, so it may stop working in a later release. An alternative technique such as use of a ContentProvider might be a better option.

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