将应用程序范围的布尔值保存在SharedPreference中 [英] Save Application Wide Boolean in SharedPreference

查看:70
本文介绍了将应用程序范围的布尔值保存在SharedPreference中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个常见的问题,我整个下午都在尝试各种似乎无效的解决方案.

I know that this is a common question asked, and I have spent all afternoon trying different solutions that don't seem to work.

我试图将布尔receiveNotifications存储在SharedPreferences中,但是当我发送通知时,它仍然会通过.当我检查所设置的活动中是否设置了布尔值时,它表示该值应该是该值,但是当我在我的Firebase MessagingService中调用该值时,它仍然允许通知通过.

I am trying to store a boolean receiveNotifications in SharedPreferences but when I send a notification it still comes through. When I check whether the boolean is set in the activity I set it in, it says that the value is what it should be, but when I call this in my Firebase MessagingService it still allows the notification to come through.

这是我第一次使用它们,因此,如果您看到明显的答案,那就是为什么.

This is my first time using them so if you see the obvious answer thats why.

存储布尔值:

// shared preferences
notificationsPref = mContext.getSharedPreferences("notifications", MODE_PRIVATE);
SharedPreferences.Editor editor = notificationsPref.edit();
                editor.putBoolean("receiveNotifications", false);
                editor.apply();

检查是否设置了布尔值:

// check if they want to receive notifications
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("notifications", MODE_PRIVATE);
Boolean areNotificationsAllowed = sharedPreferences.getBoolean("receiveNotifications", true);
if (areNotificationsAllowed){
        Toast.makeText(this, "Send Notification", Toast.LENGTH_SHORT).show();
        sendNotification(contentTitle, messageBody);
}

推荐答案

结果表明,无论您做什么,Firebase都必须覆盖您在应用程序中设置的任何内容.我不是通过Firebase控制台发送而是通过Web服务器发送通知,从而发现了这一点.通知已完全停止,并且共享首选项正常工作.

Turns out that no matter what you do Firebase must override whatever you have set in the application. I found this out by instead of sending from the Firebase console, I sent notification from my web server. The notification was stopped perfectly and the Shared Preference worked.

这篇关于将应用程序范围的布尔值保存在SharedPreference中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆