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

How to get android native push notification on cordova?

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

我正在使用带 $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 库)

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\"}"));

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

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

这是最常用的一个,效果很好