无法在Android中获取推送通知以使用ngCordova

时间:2022-02-12 22:58:12

I'm having a tough time getting push notifications (using the ngCordova plugin) to work. I have followed their sample code exactly as is documented on the site: http://ngcordova.com/docs/plugins/pushNotifications/

我很难获得推送通知(使用ngCordova插件)。我完全按照网站上记录的示例代码进行了跟踪:http://ngcordova.com/docs/plugins/pushNotifications/

(the only difference is that I don't have a deviceready listener, instead, my code is inside the ionicPlatform.ready listener.)

(唯一的区别是我没有设备监听器,相反,我的代码在ionicPlatform.ready监听器中。)

Here is my code:

这是我的代码:

angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $rootScope, $state, $cordovaPush) {
  $ionicPlatform.ready(function() {
    var config = {
      "senderID": "myID100001000"
    };

    $cordovaPush.register(config).then(function(result) {
      alert(result);
    }, function(err) {
      alert(err);
    })      
  }); 

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

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

When my app starts I do get the "OK" alert, so I know it successfully goes through the $cordovaPush.register call. However, I was expecting to get a "registered" notification event, right after, but I never get notified.

当我的应用程序启动时,我会收到“确定”警告,因此我知道它成功通过了$ cordovaPush.register调用。但是,我希望能够立即获得“注册”通知活动,但我从未收到通知。

Any help would be appreciated.

任何帮助,将不胜感激。

2 个解决方案

#1


8  

The solution is in the comments but this needs a proper answer.

解决方案在评论中,但这需要一个正确的答案。

First of all, the register callback always returns OK as long as you pass a senderID, but if the $cordovaPush:notificationReceived event is never called (it may take a few seconds), this ID is probably wrong.

首先,只要传递senderID,寄存器回调总是返回OK,但如果永远不会调用$ cordovaPush:notificationReceived事件(可能需要几秒钟),则此ID可能是错误的。

You must use the Project Number, not the Project ID.

您必须使用项目编号,而不是项目ID。

To get the number, go to the API Console, select the project and you'll be on the Overview page. On top of this page, you'll see something like this:

要获取该号码,请转到API控制台,选择项目,然后您将进入“概述”页面。在这个页面的顶部,你会看到这样的东西:

Project ID: your-project-id        Project Number: 0123456789

Just copy and use the project number and everything should work.

只需复制并使用项目编号,一切都应该有效。

#2


1  

I have suffered with this a lot and I have found out, that there are in fact two versions of the cordova push plugin currently:

我已经遭受了很多苦难,我发现,目前有两个版本的cordova push插件:

Both are supported by ngCordova, but only the deprecated version is documented.

两者都受到ngCordova的支持,但只记录了已弃用的版本。

The deprecated version is $cordovaPush and the newer one is $cordovaPushV5, and they have completely different methods.

不推荐使用的版本是$ cordovaPush,而较新的版本是$ cordovaPushV5,它们有完全不同的方法。

For me the problem was that I downloaded the cordova-plugin-push and tried to implement it with the old documentation on ngCordova site.

对我来说问题是我下载了cordova-plugin-push并尝试使用ngCordova网站上的旧文档来实现它。

The code is:

代码是:

 /*
         * Non deprecated version of Push notification events
         */
        function registerV5() {

            $ionicLoading.show({
                template: '<ion-spinner></ion-spinner>'
            });

            if (ionic.Platform.is('browser')) {
                alert("You are running on broswer, please switch to your device. Otherwise you won't get notifications");
                $ionicLoading.hide();
                return;
            }

            /**
             * Configuration doc:
             * https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
             */
            var GCM_PROJECT_ID = 'xxxxxx';

            $cordovaPushV5.initialize({
                "android": {
                    "clearNotifications": false,
                    "senderID" : GCM_PROJECT_ID
                }
            });

            $cordovaPushV5.register().then(function (deviceToken) {
                console.log("Successfully registered", deviceToken);

                $scope.data.deviceToken = deviceToken;

                // Below code required to configure $cordovaPushV5 notifications emitter. 
                // Don't pass function it's not handler.
                $cordovaPushV5.onNotification();
                $cordovaPushV5.onError();

                $ionicLoading.hide();
            }, function (error) {
                console.log("Failed to registered");
                console.log("error object : ", error);
                $ionicLoading.hide();
            });
        }

        $rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
            console.log("notification received");
            console.log("data object: ", data);

            var foreground = data.additionalData.foreground || false;
            var threadID = data.additionalData.payload.threadID || '';
            var group = data.additionalData.payload.group || false;

            if (foreground) {
                // Do something if the app is in foreground while receiving to push - handle in app push handling
                console.log('Receive notification in foreground');
            } else {
                // Handle push messages while app is in background or not started
                console.log('Receive notification in background');
                // Open FB messanger app when user clicks notification UI when app is in background.
                if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
                    if (!group)
                        // Open FB Messenger of specific user chat window
                        window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
                    else
                        // Open FB Messenger of specific group chat window
                        window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');                
            }
        });

        $rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
            console.log("notification error occured");
            console.log("event object: ", event);
            console.log("error object: ", error);
        });

More on this github article: https://github.com/driftyco/ng-cordova/issues/1125 (code from here) and in this article: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5

更多关于这篇github的文章:https://github.com/driftyco/ng-cordova/issues/1125(来自这里的代码)和本文:https://github.com/yafraorg/yafra/wiki/Blog-Ionic -PushV5

#1


8  

The solution is in the comments but this needs a proper answer.

解决方案在评论中,但这需要一个正确的答案。

First of all, the register callback always returns OK as long as you pass a senderID, but if the $cordovaPush:notificationReceived event is never called (it may take a few seconds), this ID is probably wrong.

首先,只要传递senderID,寄存器回调总是返回OK,但如果永远不会调用$ cordovaPush:notificationReceived事件(可能需要几秒钟),则此ID可能是错误的。

You must use the Project Number, not the Project ID.

您必须使用项目编号,而不是项目ID。

To get the number, go to the API Console, select the project and you'll be on the Overview page. On top of this page, you'll see something like this:

要获取该号码,请转到API控制台,选择项目,然后您将进入“概述”页面。在这个页面的顶部,你会看到这样的东西:

Project ID: your-project-id        Project Number: 0123456789

Just copy and use the project number and everything should work.

只需复制并使用项目编号,一切都应该有效。

#2


1  

I have suffered with this a lot and I have found out, that there are in fact two versions of the cordova push plugin currently:

我已经遭受了很多苦难,我发现,目前有两个版本的cordova push插件:

Both are supported by ngCordova, but only the deprecated version is documented.

两者都受到ngCordova的支持,但只记录了已弃用的版本。

The deprecated version is $cordovaPush and the newer one is $cordovaPushV5, and they have completely different methods.

不推荐使用的版本是$ cordovaPush,而较新的版本是$ cordovaPushV5,它们有完全不同的方法。

For me the problem was that I downloaded the cordova-plugin-push and tried to implement it with the old documentation on ngCordova site.

对我来说问题是我下载了cordova-plugin-push并尝试使用ngCordova网站上的旧文档来实现它。

The code is:

代码是:

 /*
         * Non deprecated version of Push notification events
         */
        function registerV5() {

            $ionicLoading.show({
                template: '<ion-spinner></ion-spinner>'
            });

            if (ionic.Platform.is('browser')) {
                alert("You are running on broswer, please switch to your device. Otherwise you won't get notifications");
                $ionicLoading.hide();
                return;
            }

            /**
             * Configuration doc:
             * https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
             */
            var GCM_PROJECT_ID = 'xxxxxx';

            $cordovaPushV5.initialize({
                "android": {
                    "clearNotifications": false,
                    "senderID" : GCM_PROJECT_ID
                }
            });

            $cordovaPushV5.register().then(function (deviceToken) {
                console.log("Successfully registered", deviceToken);

                $scope.data.deviceToken = deviceToken;

                // Below code required to configure $cordovaPushV5 notifications emitter. 
                // Don't pass function it's not handler.
                $cordovaPushV5.onNotification();
                $cordovaPushV5.onError();

                $ionicLoading.hide();
            }, function (error) {
                console.log("Failed to registered");
                console.log("error object : ", error);
                $ionicLoading.hide();
            });
        }

        $rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
            console.log("notification received");
            console.log("data object: ", data);

            var foreground = data.additionalData.foreground || false;
            var threadID = data.additionalData.payload.threadID || '';
            var group = data.additionalData.payload.group || false;

            if (foreground) {
                // Do something if the app is in foreground while receiving to push - handle in app push handling
                console.log('Receive notification in foreground');
            } else {
                // Handle push messages while app is in background or not started
                console.log('Receive notification in background');
                // Open FB messanger app when user clicks notification UI when app is in background.
                if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
                    if (!group)
                        // Open FB Messenger of specific user chat window
                        window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
                    else
                        // Open FB Messenger of specific group chat window
                        window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');                
            }
        });

        $rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
            console.log("notification error occured");
            console.log("event object: ", event);
            console.log("error object: ", error);
        });

More on this github article: https://github.com/driftyco/ng-cordova/issues/1125 (code from here) and in this article: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5

更多关于这篇github的文章:https://github.com/driftyco/ng-cordova/issues/1125(来自这里的代码)和本文:https://github.com/yafraorg/yafra/wiki/Blog-Ionic -PushV5