【发布时间】:2018-05-14 18:56:02
【问题描述】:
我知道这是一个常见的问题,我整个下午都在尝试似乎不起作用的不同解决方案。
我正在尝试在 SharedPreferences 中存储一个布尔值 receiveNotifications,但是当我发送通知时它仍然会通过。当我检查是否在我设置的活动中设置了布尔值时,它说该值是它应该是的值,但是当我在 FirebaseMessagingService 中调用它时,它仍然允许通知通过。
这是我第一次使用它们,所以如果您看到明显的答案,那就是原因。
存储布尔值:
// 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);
}
【问题讨论】:
-
你确定
getApplicationContext() == mContext? -
这可能是问题所在,
mContext = MainActivity.this -
但是当我从 Firebase 控制台发送测试通知时,它仍然会将通知发送到我的设备
-
我认为
Context在这里应该不是问题,因为getSharedPreferences是ContextWrapper的方法。Activity和Application都一样。在收到通知时调试您的代码。
标签: java android sharedpreferences firebase-cloud-messaging