Android之Shared Preferences
懶得再翻譯,這段應該很好理解,直接將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 aSharedPreferences.Editor
. - Add values with methods such as
putBoolean()
andputString()
. - 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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

posted on 2010-06-07 17:18 Eric Song 閱讀(419) 評論(0) 編輯 收藏 所屬分類: Android開發