Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...