【发布时间】:2018-04-20 01:19:14
【问题描述】:
我使用 Firebase 云消息传递 (FCM) HTTP Legacy API protocol 以 JSON 格式将推送通知发送到 android 移动设备。对于客户端,我使用 react-native-fcm 库。 目的是在应用程序处于 3 种状态时向特定设备发送通知: 1) 运行 2)后台运行 3) 被杀 根据 FCM 的文档,可以通过 FCM 服务发送 3 种不同类型的消息: 1)通知(具有预定义的字段) 2)数据(设置你想要的任何字段) 3)混合(通知+数据)。 使用 react-native-fcm 在客户端监听传入消息事件的逻辑如下:
this.notificationEmitterSubscription = FCM.on(FCMEvent.Notification, notif => {
if(notif && notif.fcm){
//received from Firebase
if(!notif.local_notification && notif.title){
let badge = parseInt(notif.badge);
FCM.setBadgeNumber(badge);
this.showNotification(notif.title, notif.body, badge);
}
//notification is clicked
if(notif.opened_from_tray){
FCM.setBadgeNumber(0);
this.executeNavigateAction(notif.fcm.action); //this method just navigates user to a particular screen in the application
}
}
});
显示通知方法是这样实现的:
showNotification(title, body, badge) {
FCM.presentLocalNotification({
body: body,
priority: "high",
title: title,
sound: "default",
large_icon: "ic_launcher",// Android only
icon: "ic_launcher",
show_in_foreground :true, /* notification when app is in foreground (local & remote)*/
vibrate: 300, /* Android only default: 300, no vibration if you pass null*/
lights: true, // Android only, LED blinking (default false)
badge: badge,
local: true,
click_action: NAV_SCREEN_NAME
});
}
notif.title、notif.body 和 notif.badge 是通过 FCM API 发送消息时在数据部分设置的字段。换句话说,消息以(3)混合形式发送:
{
"registration_ids" : ["FCM_device_token_1", "FCM_device_token_2"],
"notification" :
{
"title" : "fcm notification message title",
"body" : "fcm notification message body",
"badge" : 111
},
"data" :
{
"title" : "fcm data message title",
"body" : "fcm data message body",
"badge" : 222
}
}
如果消息是作为(1) 通知 发送的(消息中没有“数据”部分,在这种情况下,需要对读取字段进行一些更改,以更改 notif.title -> notif.fcm.title,但这不是问题的重点)或 mixed (3) 然后 当应用程序处于 (2) 后台运行和(3) 被杀。结果,没有设置徽章编号。但是,尽管未调用方法 showNotification(title, body, badge)(因为未触发事件侦听器)消息已显示。似乎 react-native-fcm 具有针对这种情况的内部实现,以在应用程序未运行时自动显示 (1) 通知和 (3) 混合消息。换句话说,仅当应用程序 (1) 运行时才调用 (1) 通知和 (3) 混合消息,而不是在应用程序处于 (2) 后台或 (3) 被杀死时调用侦听器并且不显示徽章编号。但是,消息本身会针对所有情况显示。
另一种方法是发送 (2) 数据 消息。这种类型的 FCM 消息触发侦听器 (notificationEmitterSubscription)应用程序的所有状态:(1) 运行和 (2) 后台运行和 (3) 终止。因此,所有这些州都设置了徽章编号。然而,尽管每次接收到数据 FCM 消息时都会调用方法 showNotification(title, body, badge),但如果应用程序被终止,方法 FCM.presentLocalNotification 不会显示该消息。
因此,简而言之,我有一个问题。
如何: 当 (1) 通知或 (3) 收到混合消息并且应用程序处于 (2) 后台运行或 (3) 被终止时,要么显示徽章编号 或在应用程序被 (3) 终止时显示 (2) 数据消息?
谢谢!
【问题讨论】:
-
更新: 实际上,到目前为止,我发现如果应用程序 (3) 被杀死,它不会运行事件侦听器。换句话说,我的声明: 然而,尽管方法 showNotification(title, body, badge) 在收到数据 FCM 消息时被调用,但如果应用程序被终止,方法 FCM.presentLocalNotification 不会显示该消息。有缺陷。当我通过 FCM API Legacy 协议仅发送数据消息时,我的代码中设置了徽章编号。它在 FCM 库或 android 系统中。