懒得再翻译,这段应该很好理解,直接将Dev Guide中复制过来。
The SharedPreferences
class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences
to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
To get a SharedPreferences
object for your application, use one of two methods:
getSharedPreferences()
- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences()
- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
- Call
edit()
to get a SharedPreferences.Editor
.
- Add values with methods such as
putBoolean()
and putString()
.
- Commit the new values with
commit()
To read values, use SharedPreferences
methods such as getBoolean()
and getString()
.
Here is an example that saves a preference for silent keypress mode in a calculator:
1
public class Calc extends Activity
{
2
public static final String PREFS_NAME = "MyPrefsFile";
3
4
@Override
5
protected void onCreate(Bundle state)
{
6
super.onCreate(state);
7
. . .
8
9
// Restore preferences
10
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
11
boolean silent = settings.getBoolean("silentMode", false);
12
setSilent(silent);
13
}
14
15
@Override
16
protected void onStop()
{
17
super.onStop();
18
19
// We need an Editor object to make preference changes.
20
// All objects are from android.context.Context
21
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
22
SharedPreferences.Editor editor = settings.edit();
23
editor.putBoolean("silentMode", mSilentMode);
24
25
// Commit the edits!
26
editor.commit();
27
}
28
}