使用cordova在Android / Ios中显示徽章编号

时间:2016-10-18 15:33:34

标签: android ios cordova cordova-plugins

我正在使用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);
    }
    );}

Image with badge !!

1 个答案:

答案 0 :(得分:0)

解决方案是发送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"
}

这样您就会在通知栏中收到消息。我还建议设置cordova.plugins.notification.badge.set(0) onDeviceReady和onResume事件,以便在应用程序到达前台后清除徽章编号。