【问题标题】:How to make FCM notification not show notification message when user is on the chat screen?当用户在聊天屏幕上时,如何使 FCM 通知不显示通知消息?
【发布时间】:2021-09-07 14:05:00
【问题描述】:

我正在构建一个聊天应用程序并使用 FCM 进行通知。每当用户收到新消息时,当应用处于前台时,他会收到弹出通知。

但是,我想自定义通知,使其不会显示弹出消息,而只会在用户位于聊天屏幕本身时振动。当他不在聊天屏幕上时,通知会弹出并振动。

知道如何做这个客户端吗?提前谢谢!

【问题讨论】:

  • 请贴出你的 Flutter FCM 配置代码。

标签: flutter dart firebase-cloud-messaging flutter-notification


【解决方案1】:

有两种类型的通知,数据消息和通知消息。通知消息不由您的应用处理,但您可以控制数据消息。

其次,您需要检查您是否在与向您发送消息的特定用户聊天。为了满足此要求,您可以在打开聊天室时将用户 ID 保存在任何位置(SharedPref、Utils 或任何单例),并在您离开聊天室时将其删除。现在,当您收到通知时,只需将其与您保存的用户 ID 进行比较,以确定您是要显示通知还是振动

仅振动您的手机,您可以使用包 flutter_vibrate 1.0.0 和生成通知,您可以使用包 flutter_local_notifications

FirebaseMessaging.onMessage.listen((RemoteMessage message) { 
if(message.data.senderID == prefs.getString(‘chatRoomID)){ 

   // Check if the device can vibrate
  bool canVibrate = await Vibrate.canVibrate;

 // Vibrate
 // Vibration duration is a constant 500ms because
 // it cannot be set to a specific duration on iOS.
 Vibrate.vibrate();

 // Vibrate with pauses between each vibration
final Iterable<Duration> pauses = [
const Duration(milliseconds: 500),
const Duration(milliseconds: 1000),
const Duration(milliseconds: 500),
];
// vibrate - sleep 0.5s - vibrate - sleep 1s - vibrate - sleep 0.5s - vibrate
Vibrate.vibrateWithPauses(pauses);
 } Else{  AndroidNotificationDetails(
    'your channel id', 'your channel name', 'your channel description',
    importance: Importance.max,
    priority: Priority.high,
    showWhen: false); } 
}); 

您还需要做的另一件事是在聊天屏幕中显示该新消息。为此,您可以使用 Stream Builder。

【讨论】:

  • 谢谢!所以你是说,我可以在数据消息中输入发件人的用户ID,并将其与我存储在SharedPref中的用户ID进行比较。似乎是个好主意。现在我想知道您如何控制是要振动通知还是显示通知消息?
  • 我在下面写了一些粗略的代码。你能看看评论部分,让我知道你会怎么做吗? FirebaseMessaging.onMessage.listen((RemoteMessage message) { if(message.data.senderID == prefs.getString('chatRoomID)){ //only vibrate
  • @scottlee 编辑了我的答案,但这不是将运行的实际代码。它为您提供了如何执行此操作的想法。
  • 感谢您的及时回复。我会测试一下,看看它是如何工作的。很快就会恢复:)
  • 你知道为什么我清空onMessage代码时通知仍然显示并且仍然有振动吗?以下是我的代码的一些 sn-ps:
猜你喜欢
  • 2017-09-23
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2022-09-30
  • 2013-03-24
  • 2011-11-18
  • 2020-07-14
  • 1970-01-01
相关资源
最近更新 更多