Phonegap PushPlugin 消息事件被调用两次

Phonegap PushPlugin message event gets called twice

本文关键字:两次 调用 PushPlugin 消息 事件 Phonegap      更新时间:2023-09-26

我目前正在为Android和iOS开发Phonegap 3.0应用程序。我添加了推送插件,几乎所有东西在安卓上都能正常工作,除了两件事:

1.当我收到推送通知并且我的应用当前不在前台时,该消息将显示在我的通知栏中。一旦我单击通知,应用程序就会启动,通知消息会显示两次。显示的消息是一个简单的javascript警报,其中包含通知数据,我在"onNotificationGCM"消息事件中添加了该警报。

此事件在通知栏中添加通知时第一次触发,第二次在我单击通知并启动应用时触发。因此,带有我的消息的警报功能被调用两次,并显示 2 个警报。

这是我代码中的简短片段:

onNotificationGCM: function (e) {
    switch( e.event )
    {
        case 'registered':
            if ( e.regid.length > 0 )
            {
                console.log('Regid ' + e.regid);
            }
        break;
        case 'message':
          // this is the actual push notification. its format depends on the data model from the push server
          console.log('Entered message');
          alert('message = '+e.message);
        break;
    }
}

所以我的问题是,如何防止这种情况,并且我的通知仅在打开应用程序时显示一次?

阿拉伯数字。我也有这个问题,这个问题已经在 github 存储库中作为问题发布:问题

一旦我退出我的应用程序(而不是通过设置中的"管理应用程序"菜单(,我就无法收到任何推送通知。我尝试在启动时启动我的应用程序,但这不起作用。但是当我启动应用程序时,会显示所有通知。

也许有人已经知道一些解决方法。

我还注意到,PushPlugin 使用了已弃用的 GCM 方法。有谁知道这是否是原因,为什么即使应用程序未运行也不会显示通知?

好的,所以我自己想出了我的第一点。我不再使用警报功能,而是使用使用通知插件的cordova.exec()函数。在此,我引用了一个回调函数(如果单击警报按钮(。之后,我添加了一个小标志,指示是否已看到并单击警报。只要标志显示消息尚未确认,就不会显示其他通知。瞧,当应用程序在后台运行时,通知仅显示一次。以下是简短的代码片段:

var confirmedGcmNotification = true;
...
onNotificationGCM: function (e) {
    switch( e.event )
    {
        case 'message':
            // this is the actual push notification. its format depends on the data model from the push server
            console.log('Entered message');                
            if ( e.foreground )
            {
                // When app is already open
                cordova.exec(null, null, 'Notification', 'alert', [e.message, 'Notification', 'OK']);
            }
            else
            {  // otherwise we were launched because the user touched a notification in the notification tray.
                if ( e.coldstart )
                {
                    console.log('coldstart entered');  
                    cordova.exec(null, null, 'Notification', 'alert', [e.message, 'Notification', 'OK']);
                }
                else
                {
                    console.log('Background entered');
                    if(confirmedGcmNotification) {
                        confirmedGcmNotification = false;
                        cordova.exec(PushSupport.gcmNotificationBackgroundAlert, null, 'Notification', 'alert', [e.message, 'Notification', 'OK']);
                    }
                }
            }
        break;
    }
},
gcmNotificationBackgroundAlert: function() {
    confirmedGcmNotification = true;
},

第二点有点不同。我还没有解决方案,但我检查了 android 日志并注意到,当应用程序关闭并发出新的通知时,应用程序会收到通知,但插件以某种方式错误地处理它并且不会显示它。也许很快就会有修复。