ala*_*yak 6 mobile push-notification firebase flutter firebase-cloud-messaging
我正在尝试在我的 Flutter 应用程序中使用 Firebase Cloud Messaging 实现推送通知服务。这就是 FCM 文档所说的我们应该根据应用程序的当前状态(前台、后台或终止)处理通知的方式:
Foreground:我们有一个onMessage可以监听的流,但 FCM在前台状态时不会显示任何通知,因此我们必须使用FlutterLocalNotificationsPlugin它,这是我的实现:
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
// calling flutter local notifications plugin for showing local notification
scheduleNotification(remoteMessage);
});
Run Code Online (Sandbox Code Playgroud)
在scheduleNotification方法中我调用该FlutterLocalNotificationsPlugin().show()方法,到目前为止一切都按预期工作。
问题从这里开始:
后台,终止:Firebase 在此状态下自动显示通知,并且它有一个onBackgroundMessage。方法,我们可以向该方法传递一个在FCM 显示通知后运行的BackgroundMessageHandler 。这是我的后台处理程序的实现:
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),
));
}
}
Run Code Online (Sandbox Code Playgroud)
问题:每次我的应用程序收到来自 FCM 的通知时,我的应用程序都会显示两个通知,一个由 FCM 自动显示,第二个由FlutterLocalNotificationsPlugin().show()我在BackgroundMessageHandler.
TL:博士
如何防止 FCM 自动显示任何通知并仅通过FlutterLocalNotificationsPlugin().show()方法显示?
一种解决方案是,我不从 FCM 发送通知,只发送数据消息,FCM 不显示任何通知。但是,我认为这不是正确的方法。
我在这里回答我自己的问题,经过一些研究,我在 FCM 文档中发现,如果我们想处理在客户端显示通知,它确实提到使用仅数据消息。我们可以在这里阅读相关内容
客户端应用程序负责处理数据消息。数据消息仅具有自定义键值对,没有保留键名称(见下文)。
当您希望 FCM 代表您的客户端应用程序处理显示通知时,请使用通知消息。当您想要在客户端应用程序上处理消息时,请使用数据消息。
flutter fire docs中也提到了这个东西,
然后,您的应用程序代码可以按照您认为合适的方式处理消息;更新本地缓存、显示通知或更新 UI。可能性是无止境!
这就是我猜的答案,我只是在传递 FCM 消息时不必使用“通知”字段,并且客户端上的 FCM 插件不会自动显示通知。我仍然认为这应该在文档中说得更清楚,引起了很多混乱和研究,当我们的目的是向用户显示通知时,我仍然认为这有点奇怪,但我们仍然省略了“通知”字段。
| 归档时间: |
|
| 查看次数: |
7648 次 |
| 最近记录: |