【发布时间】:2025-11-26 22:00:02
【问题描述】:
我在 onPause 方法中保存布尔值的状态。我已经尝试使用 editor.apply() 和 editor.commit() 但仍然没有保存值。 这是 onPause 方法:
@Override
protected void onPause() {
SharedPreferences.Editor editor = preferences.edit();
editor.clear(); //I have tried omitting it
editor.putBoolean(MUTE_TAG,mute);
editor.apply(); // I tried editor.commit() but with no effect
boolean mute1 = preferences.getBoolean(MUTE_TAG,false);
Log.d(TAG,"Values:\n"+ "mute1 " + mute1 + " mute);
super.onPause();
}
注意:当我尝试从不同的活动再次访问 SharedPreferences 中的值时,它不会更新。这是设置代码
public static boolean mute;
public static final String PREFS = "prefs";
init(Context context) {
preferences = context.getSharedPreferences(PREFS,MODE_PRIVATE);
mute = preferences.getBoolean(MUTE_TAG,false);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG,"MUTE PRESSED");
mute = isChecked;
break;
}
【问题讨论】:
-
不,
preferences = context.getSharedPreferences(PREFS,MODE_PRIVATE); mute = preferences.getBoolean(MUTE_TAG,false); -
去掉 clear 并在开头调用 super.onPause() 。如果你使用 apply() 或 commit() 在你的情况下并不重要。
-
请告诉我你是如何检索偏好对象的。
-
public static void init(Context context) { preferences = context.getSharedPreferences(PREFS,MODE_PRIVATE);我希望静音字段是静态的,并从 Application 类调用 init 以使静音是所有类都可以访问的公共静态字段 -
看编辑的问题
标签: android sharedpreferences onpause