Javierfdr
Javierfdr

Reputation: 1152

Shared preferences between two processes of the same application

I'm writing an Android app that contains both UI and separate processes running. I want to share simple information between the main process and a service defined in my application that is executed in a different process. I find to messy to use AIDL for inter-process communication for this purpose.

The question is: Is it safe to use Shared Preferences of the application for communicating between this two processes? This is: both read and write the same shared preferences.

I'm wondering if it actually works. In android developers reference about shared preferences (http://developer.android.com/reference/android/content/SharedPreferences.html) they state: Note: currently this class does not support use across multiple processes. This will be added later. but I don't know exactly what does this mean.

Thanks for your help

Upvotes: 25

Views: 14168

Answers (3)

David Wasser
David Wasser

Reputation: 95618

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).

Upvotes: 37

Sam
Sam

Reputation: 42407

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.

Upvotes: 0

Sam Lu
Sam Lu

Reputation: 3506

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.

Upvotes: 9

Related Questions