That instance state is provided to you again in:
• onCreate()
• onRestoreInstanceState()
It is your choice when you wish to re-apply the state data to your activity — either callback is a reasonable option.
PART 3
Data Stores, Network Services, and APIs
CHAPTER 17
Using Preferences
Android has many different ways for you to store data for long-term use by your activity. The simplest to use is the preferences system.
Android allows activities and applications to keep preferences, in the form of key/value pairs (akin to a Map
), that will hang around between invocations of an activity. As the name suggests, the primary purpose is for you to store user-specified configuration details, such as the last feed the user looked at in your feed reader, or what sort order to use by default on a list, or whatever. Of course, you can store in the preferences whatever you like, so long as it is keyed by a String
and has a primitive value (boolean, String
, etc.).
Preferences can either be for a single activity or shared among all activities in an application. Eventually preferences might be shareable across applications, but that is not supported as of the time of this writing.
To get access to the preferences, you have three APIs to choose from:
• getPreferences()
from within your Activity
, to access activity-specific preferences
• getSharedPreferences()
from within your Activity
(or other application Context
), to access application-level preferences
• getDefaultSharedPreferences()
, on PreferencesManager
, to get the shared preferences that work in concert with Android’s overall preference framework
The first two take a security-mode parameter — for now, pass in 0. The getSharedPreferences()
method also takes a name of a set of preferences — getPreferences()
effectively calls getSharedPreferences()
with the activity’s class name as the preference set name. The getDefaultSharedPreferences()
method takes the Context
for the preferences (e.g., your Activity
).
All of those methods return an instance of SharedPreferences
, which offers a series of getters to access named preferences, returning a suitably typed result (e.g., getBoolean()
to return a Boolean
preference). The getters also take a default value, which is returned if there is no preference set under the specified key.
Given the appropriate SharedPreferences
object, you can use edit() to get an “editor” for the preferences. This object has a group of setters that mirror the getters on the parent SharedPreferences
object. It also has the following:
• remove()
to get rid of a single named preference
• clear()
to get rid of all preferences
• commit()
to persist your changes made via the editor
The last one is important — if you modify preferences via the editor and fail to commit()
the changes, those changes will evaporate once the editor goes out of scope.
Conversely, since the preferences object supports live changes, if one part of your application (say, an activity) modifies shared preferences, another part of your application (say, a service) will have access to the changed value immediately.
And Now, a Word from Our Framework
Beginning with the 0.9 SDK, Android has a framework for managing preferences. This framework does not change anything mentioned previously. Instead, the framework is more for presenting consistent preference-setting options for users so different applications do not have to reinvent the wheel.
The linchpin to the preferences framework is yet another XML data structure. You can describe your application’s preferences in an XML file stored in your project’s res/xml/
directory. Given that, Android can present a pleasant UI for manipulating those preferences, which are then stored in the SharedPreferences
you get back from getDefaultSharedPreferences()
.
The following is the preference XML for the Prefs/Simple
preferences sample project available in the Source Code section at http://apress.com:
xmlns:android="http://schemas.android.com/apk/res/android">
android:key="@string/checkbox"
android:title="Checkbox Preference"
android:summary="Check it on, check it off" />
android:key="@string/ringtone"
android:title="Ringtone Preference"
android:showDefault="true"
android:showSilent="true"
android:summary="Pick a tone, any tone" />
The root of the preference XML is a PreferenceScreen
element. (I will explain why it is named that later in this chapter; for now, take it on faith that it is a sensible name.) One of the things you can have inside a PreferenceScreen
element, not surprisingly, is preference definitions — subclasses of Preference
, such as CheckBoxPreference
or RingtonePreference
, as shown in the preceding code. As one might expect, these allow you to check a checkbox and choose a ringtone, respectively. In the case of RingtonePreference
, you have the option of allowing users to choose the system-default ringtone or to choose “silence” as a ringtone.
Letting Users Have Their Say
Given that you have set up the preference XML, you can use a nearly built-in activity for allowing your users to set their preferences. The activity is “nearly built-in” because you merely need to subclass it and point it to your preference XML, plus hook the activity into the rest of your application.
So, for example, here is the EditPreferences
activity of the Prefs/Simple
project available on the Apress Web site:
packagecom.commonsware.android.prefs;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.preference.PreferenceActivity;
public classEditPreferences extendsPreferenceActivity {
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
As you can see, there is not much to see. All you need to do is call addPreferencesFromResource()
and specify the XML resource containing your preferences. You will also need to add this as an activity to your AndroidManifest.xml
file:
package="com.commonsware.android.prefs">
android:name=".SimplePrefsDemo"
android:label="@string/app_name">
android:name=".EditPreferences"
android:label="@string/app_name">
And you will need to arrange to invoke the activity, such as from a menu option, here pulled from SimplePrefsDemo
at http://apress.com:
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
Читать дальше