扑动FCM推送通知在后台获得两个通知



我正在使用一个awesome_notification包的Flutter FCM通知,我在处理onBackgroundMessage时收到两个通知。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
createNotification(message);
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

下面是我们传递给server的对象。

def send_push_notification(message, title = 'Title', channel_id)
options = {
priority: 'high',
data: { message: message },
notification: {
body: message,
title: title
title: title,
android_channel_id: channel_id
}
}
curl --location --request POST 'https://fcm.googleapis.com/fcm/send' 
--header 'Authorization: key='' 
--header 'Content-Type: application/json' 
--data-raw '{
"to" : user_token,
"notificaton": {

},
"data" : {
"channelId":"session_alert",
"title":"message title",
"body":"message body",
}
}'

然后我搜索了很多StackOverflow答案,他们告诉删除通知字段,只发送数据字段。发生的事情是一切都工作正常,并在android(前台/后台/终止)中获得通知,但在iOS(后台/前景)中获得通知,但当应用程序在iOS上处于终止状态时,我没有收到通知。

谁能告诉我如何实现正确的格式发送通知。

你可以使用firebase_messaging来代替他们正在开发的awesome_notification插件。https://pub.dev/packages/awesome_notifications。还有一件事,当你在fcm通知中有notification对象时,如果你的应用程序处于关闭状态或在后台,那么它将由系统本身自动处理。你不需要为此做任何事。

如果你只发送data对象,那么它将被应用程序处理,时间系统不能做任何事情,对于iOS它将不起作用。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
/// createNotification(message); /// comment out this code and check
}

这是因为你在json对象中添加了通知属性,FCM插件将根据你在json中传递的参数推送默认通知。第二个通知必须是您可能已经用data属性值触发的自定义通知。解决方案是在发送msg时从json中删除notification属性。我用邮差来测试这个,你也可以测试这个

{
"to" : user_token,
"notificaton": {}, // remove this 
"data" : {
"channelId":"session_alert",
"title":"message title",
"body":"message body",
}
}

我在2023年遇到同样的问题后看到了这篇文章。根据此功能请求,flutter firebase团队不打算实现允许您关闭SDK自动显示通知的功能,如果"通知";选项存在于有效负载中(doc ref)。

我试着只发送一个数据通知,但正如这里提到的,数据通知不能保证被发送。

经过大量的摆弄和调整,我已经设法通过在有效载荷中发送一个带有空白标题和正文的通知选项来解决这个问题

const message = {
notification: {
title: "",
body: "",
},
data: {
title: title,
body: body,
image: imageUrl,
},
token: registrationToken,
};

这允许我发送一个通知与应用程序终止(和后台),不被firebase SDK拦截,我可以自己处理它使用Flutter本地通知。

/// Define a top-level named handler which background/terminated messages will
/// call. Be sure to annotate the handler with `@pragma('vm:entry-point')` above the function declaration.
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
//Handle notification with your chosen notifications package here...
print('Handling a background message ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}

若要查看颤振终止的消息,请插入实际设备,然后运行"颤振日志";

希望这能帮助别人,因为我一直在寻找很长时间如何绕过这个

相关内容

最新更新