![](/img/trans.png)
[英]FCM - When app is killed/in background, app receives notification but does not play the notification sound
[英]How to show a Local Notification in Flutter, when the app is in Background/Terminated and it receives an FCM notification?
我正在嘗試在我的 Flutter 應用程序中使用 Firebase Cloud Messaging 實施推送通知服務。 根據我們應用程序的當前 state(前台、后台或終止),這就是 FCM 文檔所說的我們應該處理通知的方式:
前台:我們有一個onMessage
stream,我們可以收聽,但 FCM 在前台 state 時不會顯示任何通知,所以我們必須為此使用FlutterLocalNotificationsPlugin
,這是我的實現:
FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) {
// calling flutter local notifications plugin for showing local notification
scheduleNotification(remoteMessage);
});
在scheduleNotification
方法中,我調用了FlutterLocalNotificationsPlugin().show()
方法,到目前為止一切正常。
問題從這里開始:
背景,已終止:Firebase 在此 state 中自動顯示通知,並且它具有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),
));
}
}
問題:每次我的應用收到來自 FCM 的通知時,我的應用都會顯示兩個通知,一個由 FCM 自動顯示,第二個由我在BackgroundMessageHandler
中調用的FlutterLocalNotificationsPlugin().show()
方法顯示。
Tl:博士
如何防止 FCM 自動顯示任何通知並僅通過FlutterLocalNotificationsPlugin().show()
方法顯示它?
一種解決方案是,我不從 FCM 發送通知,只發送數據消息,FCM 不顯示任何通知。 但是,我認為這不是正確的方法。
我在這里回答我自己的問題,經過一些研究,我在 FCM 文檔中發現,如果我們想處理在客戶端顯示通知,它確實提到使用僅數據消息。 我們可以在這里閱讀
客戶端應用程序負責處理數據消息。 數據消息只有自定義鍵值對,沒有保留鍵名(見下文)。
當您希望 FCM 代表您的客戶端應用處理顯示通知時,請使用通知消息。 當您想要處理客戶端應用程序上的消息時,請使用數據消息。
flutter 火災文檔中也提到了這件事,
然后,您的應用程序代碼可以處理您認為合適的消息; 更新本地緩存、顯示通知或更新 UI。 可能性是無止境!
所以這就是我想的答案,我只是在傳遞 FCM 消息時不必使用“通知”字段,客戶端上的 FCM 插件不會自動顯示通知。 我仍然認為應該在文檔中更清楚地說明這一點,引起了很多混亂和研究,當我們的意圖是向用戶顯示通知時,我仍然認為這有點奇怪,但我們仍然省略了“通知”字段.
從上面的代碼中刪除FlutterLocalNotificationsPlugin().show
調用。 您不需要手動顯示通知。
如您所說,運行此代碼時已顯示通知。
還是我錯過了什么?
一開始我遇到了與解決方案相同的問題,我省略了 json 中的通知發送,但經過嘗試和測試,我發現我可以發送通知和數據而不會出現雙重推送通知問題,它得到了解決。
解決方案:檢查您的 onbackgroundhandler 並驗證數據 if (message.data.message ['android_channel_id'] == my channel) {
flutterLocalNotificationsPlugin.show (
);
}
fcm 服務器繼承
消息:{ to:$token 通知:$notification 數據:{title:$title body:$body id:“id”,}; }
Future<void> backgroundMessageHandler(
RemoteMessage remoteMessage) async {
if (remoteMessage.data['id'].= null) { FlutterLocalNotificationsPlugin(),show(0.remoteMessage,data['title'].remoteMessage,data['body']: NotificationDetails(android.AndroidNotificationDetails(_androidNotificationChannel,id ._androidNotificationChannel,name._androidNotificationChannel,description:icon,'launch_background':importance.Importance,max);)); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.