我知道,这是经常问的一个问题,我花了整个下午都尝试不同的解决方案,似乎并没有工作。
我想存储一个布尔receiveNotifications
在SharedPreferences但是当我发送通知仍然来通过。 当我检查布尔是否是我设置的活动设置,它说,该值是应该的,但是当我把这个在我的Firebase
的MessagingService它仍然允许通知才能通过。
这是使用它们,所以如果你看到明显的答案就是为什么我的第一次。
存储布尔:
// 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);
}
推送消息是一个JSON对象,下面的例子是直接从文档:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
}
}
有3种类型的推送消息,通知,数据,和两者;
//Notification
"message":{
"notification":{
}
}
//data
"message":{
"data":{
}
}
//both
"message":{
"notification":{
},
"data":{
}
}
每个将在应用程序取决于该应用是否打开或不会触发不同的行为。
在火力地堡Web控制台会一直发出“通知”类型,如果你添加数据,自订参数会同时发送。
你的布尔永远不会考虑采取如果应用程序被关闭,并通知来自Web的控制台。
事实证明,无论你做什么Firebase
必须覆盖不管你在应用程序中已设置。 我发现这一点的,而不是从火力地堡控制台发送,我发送的通知,从我的网络服务器。 该通知是完全停止共享偏好的工作。
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
prefs = getApplicationContext().getSharedPreferences("notifiactions",
MODE_PRIVATE);
editor = prefs.edit();
/////Assigning a Boolean///////////
editor.putBoolean("receiveNotifications", false);
editor.commit();
//Retrieving Boolean
prefs = getApplicationContext().getSharedPreferences("notifications",
MODE_PRIVATE);
bool = prefs.getBoolean("receiveNotifications", true);
//Try replacing this with your code also
if(bool){
}