In order to initialize preferences with default values from XML file describing the preferences, I can call PreferenceManager.setDefaultValues(this, R.xml.preference, false)
. Sounds simple, but I'm not quite sure when exactly should I call this?
As I understand from the docs, the above call is only needed once, in situation when no preferences are set yet. As a resu开发者_运维百科lt of this call, preferences residing in /data/data/<myapp>/shared_prefs
are going to be set, so all subsequent attempts to read preferences will get me the default values. Logically, setDefaultValues
should be called in every single code path that might be executed without preferences being already initialized. Over time, this turned out to be multiple places - main activity, another activity, background service, small BroadcastReceiver
handling system messages... Right now I've put call to setDefaultValues
in onCreate()
for my Application object, as I'm already using it as convenient singleton for other things.
Questions:
- Do I have a guarantee that every time my code executes, Application object will be created and onCreate will run?
- How are you dealing with this problem? One other way would be to hardcode default values into
getFoo(key, defValue)
calls, but that effectively scatters your default settings across whole code.
EDIT: Essentially, I don't know which solution is worse: calling setDefaultValues
every time I access prefs in given code path, or calling it in some common place (like app's onCreate) every time, no matter whether I need it or not.
I'm going to delete my original answer and answer the questions that you actually asked.
- Yes, the Application object's onCreate will be executed at the start of every process. Keep in mind that doesn't guarantee it will be run each time you start your main activity. If Android still has your process running it will use that again (e.g. you still have a service running). So yes what you're doing will work and you're correct in observing it won't blow up.
- I'm dealing with this problem by subclassing SharedPreferences (let's call it
MyPrefs
-- that's not what I call it but that's not important). The key features of MyPrefs are:- encapsulation of get/set methods instead of directly accessing the key names
- Handling code for loading defaults. I'm being a little lazy by using a static boolean instead of an AtomicBoolean to tell me if the defaults have been loaded.
Having said that... it works for me, but if you're almost certain you'll be calling the SharedPreferences every time your code runs where you're at works as good as any.
Hope this helps more than my previous answer.
精彩评论