当应用在后台时,点击通知时 fcm.onNotification() 方法未被调用

4

我已经安装了cordova-plugin-fcm,一切都很正常,除了一个小问题。当应用程序在后台/关闭时,从Firebase发送推送通知,通知会在设备上弹出。在托盘中点击该通知后,我的应用程序开始运行,但控制权不会进入fcm.onNotification()。

我的app.component.ts中的代码如下:

   fcm.onNotification().subscribe(data=>{
     if(data.wasTapped){
       console.log("Received in background");
       console.log(data);
     } else {
      console.log("Received in foreground");
      console.log(data);
     };
   });
1个回答

17

通知应该在 "click_action":"FCM_PLUGIN_ACTIVITY" 中包含,以便能够触发 onNotification(),如果您从 Firebase 控制台发送通知,则无法起作用,请使用 HTTP 请求发送通知,请参考Firebase Cloud Messaging HTTP Protocol documentation 了解更多信息,我建议使用Postman 来实现,它也是 Chrome 插件。

您的代码应该如下所示:

{
  "notification":{
    "title":"Notification title",
    "body":"Notification body",
    "sound":"default",
    "click_action":"FCM_PLUGIN_ACTIVITY", //this is needed so the onNotification() fires when notification is tapped
    "icon":"fcm_push_icon"
  },
  "data":{
    "param1":"value1",
    "param2":"value2"
  },
  "to":"/topics/topicExample"(or device token),
  "priority":"high"
}

参考资料:

这两个链接包含了你需要的一切。

祝好运!


1
太好了!!它有效了。只需添加 click_action="FCM_PLUGIN_ACTIVITY",然后将调用函数fcm.onNotification()。谢谢。 - Eggy
是的,我已经像上面那样做了,没有任何变化...也没有错误。我正在尝试通过后端进行通知。 - Joe Sleiman
我有同样的问题。我收到了通知,但是fcm.onNotification没有触发。@JoeSleiman,你能解决这个问题吗?我创建了这个问题https://stackoverflow.com/questions/58418159/ionic-push-notification-method-fcm-onnotification-not-work-when-app-is-open-r - victorpacheco3107
@George,感谢您指导我找到解决方案。它有效。顺便问一下,当应用程序在前台时如何收集通知数据?如果只有在点击数据时才调用fcm.onNotification(),那么在应用程序在前台时是否有任何方法可以从通知中获取数据? - vigamage
@vigmage 当然可以。当我回答那个问题的时候,我正在使用ionic 1项目并使用FCMPlugin插件。要读取通知:FCMPlugin.onNotification(function (data) {}),数据对象包含一个wasTapped布尔值,如果为true,则表示数据已被点击;如果为false,则表示应用程序在前台。 - George
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接