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:

  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. 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:


1publicclassCalcextendsActivity {
2publicstaticfinalStringPREFS_NAME="MyPrefsFile"
;
3

4
@Override
5protectedvoidonCreate(Bundlestate)
{
6super
.onCreate(state);
7
...
8

9//Restorepreferences

10SharedPreferencessettings=getSharedPreferences(PREFS_NAME,0);
11booleansilent=settings.getBoolean("silentMode",false
);
12
setSilent(silent);
13}

14
15
@Override
16protectedvoidonStop()
{
17super
.onStop();
18

19//
WeneedanEditorobjecttomakepreferencechanges.
20//Allobjectsarefromandroid.context.Context

21SharedPreferencessettings=getSharedPreferences(PREFS_NAME,0);
22SharedPreferences.Editoreditor=
settings.edit();
23editor.putBoolean("silentMode"
,mSilentMode);
24

25//Committheedits!

26editor.commit();
27}

28}

更多相关文章

  1. 深入理解Android(安卓)Notifiction机制
  2. Android(安卓)复制和粘贴功能
  3. 理解Android中垃圾回收日志信息
  4. Android(安卓)Studio——理解Intent和Intent Filter
  5. Android(安卓)Permission的 protectLevel的理解
  6. Android剪切板(ClipboardManager)复制文本
  7. Android(安卓)深入理解 View 的绘制流程和机制
  8. Android(安卓)调用系统相机回调后的处理
  9. 菜鸟对使用AIDL的一点理解

随机推荐

  1. android 中的MultipartEntity 类
  2. android > CallLog 通话记录
  3. Android:自定义Dialog
  4. 学习使用DrawerLayout
  5. android 自定义view 类似loadding从下往
  6. 友盟全域指数
  7. Android积木之PopupWindow
  8. Android 使用des算法
  9. Android调用浏览器打开网页内容
  10. Android--掌握日志工具的使用