【发布时间】:2021-07-02 16:01:01
【问题描述】:
我正在尝试在我的 Flutter 应用中使用 Firebase Cloud Messaging 实施推送通知服务。这就是 FCM 文档所说的我们应该根据应用的当前状态(前台、后台或终止)处理通知的方式:
前台:我们有一个 onMessage 流,我们可以收听,但 FCM 在前台状态时将不显示任何通知,所以我们必须使用FlutterLocalNotificationsPlugin 为此,这是我的实现:
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
// calling flutter local notifications plugin for showing local notification
scheduleNotification(remoteMessage);
});
在scheduleNotification 方法中我调用FlutterLocalNotificationsPlugin().show() 方法,到目前为止一切正常。
问题从这里开始:
Background, Terminated:Firebase 会在此状态下自动显示通知,它有一个 onBackgroundMessage. 方法,我们可以将 BackgroundMessageHandler 传递给该方法在之后运行FCM 已显示通知。这是我对后台处理程序的实现:
Future<void> backgroundMessageHandler(
RemoteMessage remoteMessage) async {
RemoteNotification? remoteNotification = remoteMessage.notification;
if (remoteNotification != null) {
FlutterLocalNotificationsPlugin().show(
remoteMessage.messageId.hashCode,
remoteNotification.title,
remoteNotification.body,
NotificationDetails(
android: AndroidNotificationDetails(
_androidNotificationChannel.id,
_androidNotificationChannel.name,
_androidNotificationChannel.description,
icon: 'launch_background',
importance: Importance.max),
));
}
}
问题:每次我的应用收到 FCM 的通知时,我的应用都会显示 两个 通知,一个由 FCM 自动显示,第二个由我在BackgroundMessageHandler 中调用的FlutterLocalNotificationsPlugin().show() 方法。
Tl:dr
如何防止 FCM 自动显示任何通知并仅通过 FlutterLocalNotificationsPlugin().show() 方法显示?
一种解决方案是,我不从 FCM 发送通知,而只发送数据消息,而 FCM 不显示任何通知。但是,我不认为这是正确的方法。
【问题讨论】:
-
阅读此文,或许能有所帮助:stackoverflow.com/questions/66934956/…
-
你用什么来发送通知?
-
@CeltK.B.正如我在问题中提到的,我确实需要 onMessage 侦听器,当应用程序处于前台时,FCM 不会显示任何通知,只有 FlutterLocalNotifiationPlugin 会显示。这正是我想要的。问题是,当应用程序处于后台时,在这种情况下,FCM 显示一个通知,而 FlutterLocalNotificationPlugin 也显示一个通知,所以我得到 2 个通知,而不是一个。我希望 FCM 在任何状态下都不显示通知。
-
哟,可以看到你的代码吗?只是
_firebaseMessagingBackgroundHandler()部分?基本上,我只能在main() {}上面定义这个,这让我很头疼!如果我将其声明到其他地方,则会收到Null check operator used on a null value错误。如果我只使用data发送,那么它在 iOS 上不起作用?你也让它在 iOS 上运行吗?
标签: firebase flutter mobile push-notification firebase-cloud-messaging