在使用 SharedPreferences 存储数据时,需要在 Activity 的 onPause() 方法中提交更改,这样才能确保在应用关闭或意外终止时保存数据。
示例代码:
// 获取 SharedPreferences 对象 SharedPreferences preferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE); // 获取 SharedPreferences 编辑器 SharedPreferences.Editor editor = preferences.edit(); // 存储数据 editor.putString("key", "value"); // 提交更改 editor.apply(); // 或者 editor.commit();
// 在 Activity 的 onPause() 方法中提交更改 @Override protected void onPause() { super.onPause(); editor.apply(); // 或者 editor.commit(); }