我有推插件https://github.com/phonegap-build/PushPlugin.git配置cordova 3.5。当应用程序处于前台时,通知插件回调被调用,一切都按预期工作。
当应用程序处于非活动状态(在后台)时,收到通知,我可以在通知栏中看到它们,但回调函数没有被调用。我的代码是基于在推插件给出的例子。下面是我的代码简化,以重现这个问题,
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.
我有一个类似的问题与Cordova 3.5.0和PushPlugin 2.2.0:通知工作时,应用程序在前台,但不是当它在后台或不运行。我通过阅读PushPlugin的源代码(文件src/com/plugin/gcm/GCMIntentService.java)找到了解决方案:通知的有效载荷必须包括"message"one_answers"msgcnt"键。
另外,如果您使用PhoneGap,请确保在消息中包含所需的属性。从phonegap推送插件doc:
在Android上,如果你想让你的On ('notification')事件处理程序是当你的应用程序在后台时调用,你从GCM发送的JSON会需要包含"content-available": "1"。
我使用Ruby gem Rpush,并花了很多时间弄清楚为什么当应用程序在后台时'notification'处理程序没有被触发。最终工作的代码如下所示:
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!
查看"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).
所以在后台模式下,你的" onnotificationongcm "方法只会在以下情况下被调用:
- 如果通知显示在警报视图中,用户选择"视图"选项[适用于iOS平台]
- 用户从设备通知托盘中选择通知[适用于iOS和android]
对于我来说,onNotification函数也没有被调用,甚至当应用程序在前台时也没有。
在互联网上阅读,我确保发件人ID是100%正确的,因为注册函数即使错误也会返回成功。
现在你建议清除Dalvik缓存,这似乎需要安装一个root设备或恢复工具(我的Galaxy Nexus测试设备默认没有)。尽管如此,我还是尝试重命名应用程序,希望它不会使用当前的缓存。这工作。
解决问题的步骤:
- 在
config.xml
文件中修改小部件id
的值 - 在应用程序设置 中从手机删除应用程序
- 在我的情况下,从Phonegap构建服务中删除应用程序并创建一个新的(不确定这是必要的)
- 重新构建并部署应用程序
启动并运行,onNotification函数开始工作!:)
同样的事情又开始发生了,我试图阻止我的设备扎根,因为它需要一个完整的擦除,但我同样的修复没有再次工作第二次。
在设备启动并安装恢复工具后,清除Dalvik缓存确实奏效了…
根据FactualHarmony的第三个答案,我还查看了下面的源代码/src/android/com/plugin/gcm/GCMIntentService.java。
你必须有"message"one_answers"msgcnt"键在你的消息使它工作时,应用程序是在后台,它为我工作。