0

我想使用SharedPreferences检索SwitchPreference的值,但它不工作。我使用SwitchPreference,以便用户可以打开/关闭通知,但无论值是什么,它都会显示通知。 这是代码。Android SwitchPreference不起作用

NotificationUtils.java

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); 
    if (preferences.getBoolean("notification_key", true)) { 
     notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build()); 
    } 

的preferences.xml

<SwitchPreference 
    android:contentDescription="Turn notifications on/off" 
    android:defaultValue="true" 
    android:key="notification_key" 
    android:summaryOff="Off" 
    android:summaryOn="On" 
    android:title="Notifications" /> 

我也无效,在SettingsFragment.java注册的OnSharedPreferenceChange听众。

回答

0

我解决了这个问题,实际上这个值并没有切换,在设置屏幕中,Switch关闭和打开,但是这个值仍然是默认值。通过在OnPreferenceChangeListener中设置新值并解决该问题,解决了这个问题。

0

尝试

PreferenceManager.getDefaultSharedPreferences(context); 

更换

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE); 

我相信你试图从错误SharedPreferences检索"notification_key",这就是为什么它总是使用true的默认值,并显示您的通知。

编辑:您可以检查看看SharedPreferences您正在使用中是否包含与contains()法“notification_key”键。

+0

我已经使用了getDefaulSharedPreferences(context)方法,但是会发生同样的事情,如果键存在且返回true,则使用contains方法进行检查。当使用getBoolean方法时,无论布尔defValue我提供的是获取设置并显示通知,如果设置为true,无论交换机的状态如何,并且如果defValue设置为false,则即使开关状态为开,它也不会显示通知。我无法弄清楚那里发生了什么。 –