如何在cordova上获得android原生推送通知?

时间:2015-12-15 11:26:25

标签: android cordova notifications push pushsharp

当服务器发送通知时,将触发应用程序上的事件,但我只获得带有应用消息的警报,而不是本机通知。

我正在使用带有$ cordovaPush插件的离子框架。在服务器端,我使用PushSharp库来调用GCM。

这是在$ ionicPlatform.ready

上添加到app.js的代码

 var androidConfig = {
            badge: true,
            sound: true,
            alert: true,
            "senderID": "10xxxxxxxxxx"
        };

$cordovaPush.register(androidConfig).then(function (result) {
  // Success
}, function (err) {
  // Error
})

$rootScope.$on('$cordovaPush:notificationReceived', function (event, notification) {
  alert('$cordovaPush:notificationReceived');
  switch (notification.event) {
    case 'registered':
      if (notification.regid.length > 0) {
        alert('registration ID = ' + notification.regid);
      }
      break;

    case 'message':
      // this is the actual push notification. its format depends on the data model from the push server
      alert(JSON.stringify(notification));
      break;

    case 'error':
      alert('GCM error = ' + notification.msg);
      break;

    default:
      alert('An unknown GCM event has occurred');
      break;
  }
}, false);

这是来自服务器的代码(C#+ PushSharp lib)

var push = new PushBroker();
//Wire up the events for all the services that the broker registers
push.OnNotificationSent += NotificationSent;
push.OnChannelException += ChannelException;
push.OnServiceException += ServiceException;
push.OnNotificationFailed += NotificationFailed;
push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
push.OnChannelCreated += ChannelCreated;
push.OnChannelDestroyed += ChannelDestroyed;

push.RegisterGcmService(new
                        GcmPushChannelSettings("AIxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));

push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(
  "APAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                       .WithJson("{\"alert\":\"Hello World!\",\"badge\":7,\"sound\":\"sound.caf\"}"));

1 个答案:

答案 0 :(得分:1)

我没有使用过这个插件,但我推荐你这个:

https://github.com/phonegap/phonegap-plugin-push

这是最常用的,它就像一个魅力