Cordova PushPlugin onNotification ecb not fired

2019-06-07 15:13发布

myApp.services.factory('GCMHelper', ($q)->

  pushNotification = {}

  _init = ()->
    defer = $q.defer()

    ionic.Platform.ready(()->
      pushNotification = window.plugins.pushNotification;
      window.onNotification = (res)->
        console.log('onNotification', res)
      defer.resolve()
    )

    return defer.promise

  return {
    register: ()->
      _init().then(()->
        pushNotification.register(
          (res)->
            console.log('gcm register success', res)
          (err)->
            console.log('gcm register err', err)
          {
            "senderID": "*********",
            "ecb": "onNotification"
          }
        );
      )
  }
)

in controller:

GCMHelper.register()

(Please excuse my poor English) I'm tring Cordova PushPlugin with Cordova 4.2 and Ionic beta 14, it got success callback every time with "OK" string, but ecb onNotification never fired, and no error at console. I almost have no ideal with that..., any one help?

1条回答
淡お忘
2楼-- · 2019-06-07 16:04

Use the following for Push Notification in Android and iOS. It will work properly for you. After install the app, user will need to open the app for call ecb methods. In iOS, PushNotifcation's register success method will returns the mobile register id in result but in android, it will return only OK. In Android, onNotificationGCM method will be called for two type event 1) RegisterId and 2) Notification Message. I have also added the showNotificationAPN/GCM method for show notification popups with $ionicPopup.alert().

.run(function ($ionicPlatform, PushProcessingService) {

    $ionicPlatform.ready(function () {
        try {
            PushProcessingService.initialize();
        } catch (e) {
            //hide event
        }
    })
})

.factory('PushProcessingService', ["$window", "$ionicPopup", function ($window, $ionicPopup) {
    function onDeviceReady() {
        var pushNotification = window.plugins.pushNotification;
        if (ionic.Platform.isAndroid()) {
            pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {'senderID': 'XXXXXXXXXXXXXX', 'ecb': 'onNotificationGCM'});
        } else if (ionic.Platform.isIOS()) {
            var config = {
                "badge": "true",
                "sound": "true",
                "alert": "true",
                "ecb": "pushCallbacks.onNotificationAPN"
            };
            pushNotification.register(gcmSuccessHandler, gcmErrorHandler, config);
        }

        var addCallback = function addCallback(key, callback){
            if(window.pushCallbacks == undefined){
                window.pushCallbacks = {};
            }
            window.pushCallbacks[key] = callback({registered:true});
        }
    }

    function gcmSuccessHandler(result) {
        console.log("Register push notification successfully : " + result);
        if (ionic.Platform.isIOS()) {
            var mobileType = "ios";
            var mobileRegisterId = result;
            // Save the ios mobile register Id in your server database
            // call the following method on callback of save
                addCallback("onNotificationAPN", onNotificationAPN);            
        }
    }

    function gcmErrorHandler(error) {
        console.log("Error while register push notification : " + error);
    }

    return {
        initialize: function () {
            document.addEventListener('deviceready', onDeviceReady, false);
        },
        registerID: function (id) {
            var mobileType = "android";
            // Save the android mobile register Id in your server database
            console.log("RegisterId saved successfully.");
        },
        showNotificationGCM: function (event) {
            $ionicPopup.alert({
                title: "Pajhwok Notification",
                subTitle: event.payload.type,
                template: event.payload.message
            });
        },
        showNotificationAPN: function (event) {
            $ionicPopup.alert({
                title: event.messageFrom + "..",
                subTitle: event.alert,
                template: event.body
            });
        }
    }
}])

onNotificationAPN = function(event) {
    if (!event.registered) {
        var elem = angular.element(document.querySelector('[ng-app]'));
        var injector = elem.injector();
        var myService = injector.get('PushProcessingService');
        myService.showNotificationAPN(event);
    } else {
        console.log("Registered successfully notification..");
    }
}

function onNotificationGCM(e) {
    switch( e.event )
    {
        case 'registered':
            if ( e.regid.length > 0 )
            {
                // Your GCM push server needs to know the regID before it can push to this device
                // here is where you might want to send it the regID for later use.
                var elem = angular.element(document.querySelector('[ng-app]'));
                var injector = elem.injector();
                var myService = injector.get('PushProcessingService');
                myService.registerID(e.regid);
            }
            break;

        case 'message':
            // if this flag is set, this notification happened while we were in the foreground.
            // you might want to play a sound to get the user's attention, throw up a dialog, etc.
            var elem = angular.element(document.querySelector('[ng-app]'));
            var injector = elem.injector();
            var myService = injector.get('PushProcessingService');
            myService.showNotificationGCM(e);
            break;

        case 'error':
            alert('<li>ERROR :' + e.msg + '</li>');
            break;

        default:
            alert('<li>Unknown, an event was received and we do not know what it is.</li>');
            break;
    }
}
查看更多
登录 后发表回答