[英]Display badge number in Android/Ios using cordova
我正在使用cordova開發一個混合應用程序。我希望在從APNS / FCM收到通知后,在與下圖相同的應用程序圖標中顯示通知計數。 我正在使用cordova-plugin-fcm和cordova-plugin-badge插件。
代碼:
onDeviceReady: function() {
cordova.plugins.notification.badge.hasPermission(function (granted) {
});
cordova.plugins.notification.badge.registerPermission(function (hasPermission) {
});
// switch on 'auto clear'
cordova.plugins.notification.badge.configure({
autoClear: true
});
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
//Keep in mind the function will return null if the token has not been established yet.
FCMPlugin.getToken(
function(token){
console.log("token "+token);
},
function(err){
console.log('error retrieving token: ' + err);
}
)
//FCMPlugin.subscribeToTopic( topic, successCallback(msg), errorCallback(err) );
//All devices are subscribed automatically to 'all' and 'ios' or 'android' topic respectively.
//Must match the following regular expression: "[a-zA-Z0-9-_.~%]{1,900}".
FCMPlugin.subscribeToTopic('all');
//FCMPlugin.onNotification( onNotificationCallback(data), successCallback(msg), errorCallback(err) )
//Here you define your application behaviour based on the notification data.
FCMPlugin.onNotification(
function(data){
//increase the badge
cordova.plugins.notification.badge.increase();
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
}
},
function(msg){
console.log('onNotification callback successfully registered: ' + msg);
},
function(err){
console.log('Error registering onNotification callback: ' + err);
}
);}
解決方案是發送2個不同的FCM消息。
第一個沒有通知的負載,如下所示:
{
"data":{
"badge":"true",
},
"to":"/topics/all",
"priority":"high"
}
這將觸發MyFirebaseMessagingService.java中的onMessageReceived,然后將有效負載推送到FCMPlugin.onNotification()回調。
FCMPlugin.onNotification(function(data){
if(data.badge == "true"){
cordova.plugins.notification.badge.increase();
}
});
這樣,您將增加徽章編號。 然后,您使用如下有效負載發送通知:
{
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"to":"/topics/all",
"priority":"high"
}
這樣,您將在通知托盤中收到消息。 我還建議在deviceReady和onResume事件上設置cordova.plugins.notification.badge.set(0)
,以便在應用程序進入前台后清除徽章編號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.