问题
I'm building an app with a PreferenceActivity and a Service (running in its own remote process due to android:process=":remote" flag) and both need to access programmatically the SharedPreferences. At present time I'm getting a SharedPreference object with the following code that uses the getSharedPreferences method defined in both Service and PreferenceActivity classes:
SharedPreferences sharedPrefs = getSharedPreferences("com.mypackage_preferences", MODE_PRIVATE, MODE_MULTI_PROCESS)
Is this the same as the following?
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences()
1) In the second one I can not specify flags, or is there a way to specify them?
2) Do I really need to specify MODE_MULTI_PROCESS since I'm accessing/modifying the shared preferences from both Service and PreferenceActivity? I think that most of the time you have a PreferenceActivity that modifies the properties and another Activity that reads/modifies them, so is MODE_MULTI_PROCESS needed almost always or is it only needed when there are multiple and possibly concurrent accesses to the SharedPreferences (as in my case, with the background service that can be active while you're editing preferences in PreferenceActivity)
3) The documentation of MODE_MULTI_PROCESS says This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file, does this mean that my Service and my PreferenceActivity can point different preference files? How do you change the preference file name in a PreferenceActivity?
4) Shared preferences are named in this way because they are shared among all the components (activities, services etc) of your application, right? Non shared preferences (i.e. the ones you can get with getPreferences() in you activity) are local to the component that creates them but are being saved in the same *com.mypackage_preferences* file? This could answer to my doubts in point 3)
回答1:
You only need MODE_MULTI_PROCESS
if you are accessing the preferences from different processes. If you just have different activities that are using the shared prefs then you don't need MODE_MULTI_PROCESS
.
You mention that you have a service. As long as the service is running in the same process as the activities you still don't need MODE_MULTI_PROCESS
. The service will run by default in the same process unless you have specified android:process="..."
in the <service>
tag in the manifest.
回答2:
The other big advantage: garbage collects in a busy service don't interfere with animations in the user interface.
来源:https://stackoverflow.com/questions/10546511/managing-sharedpreferences-in-both-preferenceactivity-and-service-within-same-ap