![](/img/trans.png)
[英]Is there any way to implement push notifications with action buttons in flutter? Using firebase_messaging
[英]Flutter push notifications app background : firebase_messaging
我想在我的应用程序处于后台时显示推送通知。
我正在使用flutter_local_notifications package 和firebase_messaging package。
推送通知与 firebase_messaging 以及我的应用程序作为后台时配合得很好。
但是,下面的方法:
// The following handler is called, when App is in the background.
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
如果RemoteNotification
object 通过RemoteMessage
传递,则不会调用:
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('message from background handler');
print("Handling a background message: ${message.messageId}");
// If this is null, then this handler method is called
RemoteNotification remoteNotification = message.notification;
showNotificationFromData(message.data);
}
因此,我必须传递message.data
object 这是一个Map<String, dynamic>
。
我的问题是,当调用此firebaseMessagingBackgroundHandler
处理程序方法时,我不再收到推送通知。
所以我一直在尝试使用flutter_local_notification
package 来显示推送通知,但正如所说,它是“本地”的,所以它在前台工作正常但显然不在后台(相同的代码,相同的数据未显示在后台作为推送通知)。
问题:
我需要调用firebaseMessagingBackgroundHandler
处理程序来处理我的应用程序中的事件。 所以当我的应用程序在后台时,我可以做些什么来仍然有推送通知吗?
谢谢
好的,我找到了解决方案。 它是在服务器端代码中将content_available
值设置为True
。
要替换firebase_messaging.Notification
项,我们需要覆盖android
和apns
配置。
这在 python 中看起来像这样:
apnsConfig = messaging.APNSConfig(
payload=messaging.APNSPayload(
aps=messaging.Aps(
content_available=True,
)
),
)
我现在正在接收推送通知并调用 dart 代码中的后台处理程序。
我知道这有点太晚了,但任何人都试图使用 firebase 获得自定义通知,那么这里是解决方案
对于 Android(颤振)
在 Android 上,通知消息被发送到用于控制通知传递方式的通知通道。 使用的默认 FCM 通道对用户是隐藏的,但提供了“默认”重要性级别。 注意通知需要“最大”重要性级别。
这意味着我们需要首先创建一个具有最高重要性级别的新通道,然后将传入的 FCM 通知分配给该通道。 我们可以利用flutter_local_notifications
package
flutter_local_notifications
package 添加到本地项目。const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.max,
);
(请记住,这是示例代码,但您可以通过通知渠道代码自定义通知)
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
android/app/src/main/AndroidManifest.xml
文件。 在application
组件中添加以下meta-data
模式: <meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
现在,每当您发送通知时指定您的频道 ID,您的应用程序会自动显示您的自定义通知(通过 api 或 firebase 控制台)
{
"message":{
"token":"token_1",
"android_channel_id":"high_importance_channel" //specify channel id here
"data":{},
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message!",
}
}
}
至于ios ,他们不支持通知渠道,我没有必要的资源和信息,如果你们知道下面的评论将会非常有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.