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. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android打电话、发短信实现
  2. Vibrator
  3. Android在线资源API
  4. Android Activity设置无标题和全屏
  5. Android HAL 研究开发 FOR LED
  6. Android 热更新ICON图标
  7. android之通过URL来获取网络资源并下载资
  8. React-Native搭建报错:Unable to load scr
  9. Android(安卓)Gradle 多渠道打包
  10. ConstraintLayout + CardView + Space +