且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Android 中使用 SharedPreferences 来存储、获取和编辑值

更新时间:2023-01-06 12:44:17

要获取共享首选项,请使用以下方法在您的活动中:

To obtain shared preferences, use the following method In your activity:

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 的示例目录包含检索和存储共享首选项的示例.它位于:

The android sdk's sample directory contains an example of retrieving and storing shared preferences. Its located in the:

<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory

编辑==>

我注意到,在这里写下 commit()apply() 之间的区别也很重要.

I noticed, it is important to write difference between commit() and apply() here as well.

commit() 如果值保存成功则返回 true 否则返回 false.它将值同步保存到 SharedPreferences.

commit() return true if value saved successfully otherwise false. It save values to SharedPreferences synchronously.

apply() 是在 2.3 中添加的,无论成功还是失败都不会返回任何值.它会立即将值保存到 SharedPreferences,但会启动一个异步提交.更多细节在这里.