Android之Shared Preferences
16lz
2022-03-14
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}
更多相关文章
- 深入理解Android(安卓)Notifiction机制
- Android(安卓)复制和粘贴功能
- 理解Android中垃圾回收日志信息
- Android(安卓)Studio——理解Intent和Intent Filter
- Android(安卓)Permission的 protectLevel的理解
- Android剪切板(ClipboardManager)复制文本
- Android(安卓)深入理解 View 的绘制流程和机制
- Android(安卓)调用系统相机回调后的处理
- 菜鸟对使用AIDL的一点理解