6

我有 使用cordova 3.5配置的推送插件https://github.com/phonegap-build/PushPlugin.git 。当应用程序在前台时,通知插件回调被调用,一切都按预期工作。

当应用程序处于非活动状态(在后台)时,会收到通知,我可以在通知栏中看到它们,但不会调用回调函数。我的代码基于推送插件中给出的示例。下面是我简化的代码以重现该问题,

 initialize : function () {
    console.info('NOTIFY  Ready to register for push notification.');
    var pushNotification = window.plugins.pushNotification;
    // Register device with push server
    pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {
          'senderID': GCM_SENDER_ID,
          'ecb': 'onNotificationGCM'
     });

 }

window.onNotificationGCM = function(notification){ 
    //the beep is invoked 3 times only when the app is in foreground
navigator.notification.beep(3);
    console.log('EVENT -> RECEIVED:' + notification.event + '');

}

一天多来,我一直在为这个问题头疼。任何帮助表示赞赏。

更新: 我终于找到了问题所在。我必须清除 dalvik 缓存并重新启动手机。到目前为止发生在我身上两次。似乎是 android 中的一个已知问题,https://github.com/phonegap-build/PushPlugin/issues/35

4

5 回答 5

13

我在使用 Cordova 3.5.0 和 PushPlugin 2.2.0 时遇到了类似的问题:当应用程序在前台时通知有效,但在后台或未运行时无效。我通过阅读 PushPlugin 的源代码(文件 src/com/plugin/gcm/GCMIntentService.java)找到了解决方案:通知的有效负载必须包含“message”和“msgcnt”键。

于 2014-07-28T19:32:43.683 回答
4

此外,如果您使用 PhoneGap,请确保您在消息中包含所需的属性。来自phonegap 推送插件文档

在 Android 上,如果您希望在应用处于后台时调用 on('notification') 事件处理程序,则从 GCM 发送的 JSON 将 需要包含 "content-available": "1"

我使用 Ruby gem Rpush 并花了很多时间弄清楚为什么当应用程序在后台时不会触发“通知”处理程序。最终工作的代码如下所示:

n = Rpush::Gcm::Notification.new
n.app = Rpush::Gcm::App.find_by_name("MyApp")
n.registration_ids = [ 'xxxxxxxxx' ]
n.data = { 
  title: "Message Title",
  message: "Message Body",
  sound: "default",
  'content-available' => "1"
}
n.save!
于 2016-04-25T09:23:12.623 回答
0

如果您查看“ecb”的文档https://github.com/phonegap-build/PushPlugin#ecb-amazon-fire-os-android-and-ios

Your app may receive a notification while it is active (INLINE). 
If you background the app by hitting the Home button on your device, you may later receive a status bar notification. 
Selecting that notification from the status will bring your app to the front and allow you to process the notification (BACKGROUND).

因此,在后台模式下,您的“onNotificationGCM”方法将仅在以下情况下被调用:

  1. 如果通知显示在警报视图中并且用户选择“查看”选项 [适用于 iOS 平台]
  2. 用户从设备通知托盘中选择通知 [适用于 iOS 和 android]
于 2014-06-28T09:04:14.597 回答
0

对我来说,onNotification 函数也没有被调用,即使应用程序在前台也不被调用。

在互联网上阅读我确保发件人 ID 是 100% 正确的,因为即使注册功能出错,它也会返回成功。

现在您建议清除 Dalvik 缓存,这似乎需要安装有根设备或恢复工具(我的 Galaxy Nexus 测试设备默认没有安装)。仍然这让我尝试重命名应用程序,希望它不会使用当前缓存。这行得通。

我解决问题的步骤:

  • 更改文件id中的小部件值config.xml
  • 在应用程序设置中从手机中删除应用程序
  • 在我的情况下,从Phonegap 构建服务中删除了该应用程序并创建了一个新应用程序(不确定是否有必要)
  • 重建和部署应用程序

启动并运行,onNotification 功能开始工作!:)

更新

同样的事情再次发生,我试图阻止我的设备生根,因为它需要完全擦除,但我的相同修复第二次没有再次起作用。

在 root 设备并安装恢复工具后,擦除 Dalvik 缓存确实可以解决问题......

于 2014-08-30T09:19:57.213 回答
0

根据 FactualHarmony 的第三个回答,我还查看了 /src/android/com/plugin/gcm/GCMIntentService.java 下的源代码。

您的消息中必须有“message”和“msgcnt”键,以使其在应用程序在后台运行并且对我有用。

希望这可以帮助。

于 2015-04-29T04:55:03.747 回答