Android之Shared Preferences
16lz
2021-01-23
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:
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);
12setSilent(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}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer