要获取共享首选项,请使用以下方法 在您的活动中:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
要阅读首选项:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
编辑和保存首选项
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();
android sdk的示例目录包含一个检索和存储共享首选项的示例.其位于:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Edit==>
我注意到,在这里写下commit()
和apply()
之间的差异也很重要.
100如果成功保存值,则返回true
,否则返回false
.它将值保存到SharedReferences synchronously.
101是在2.3中添加的,无论是成功还是失败都不会返回任何值.它立即将值保存到SharedPreferences,但启动asynchronous提交. 更多详细信息是here.