即使应用程序被终止也显示 Flutter 通知

olo*_*olo 5 flutter firebase-cloud-messaging

我正在尝试显示通过 FCM 发送到 Android 设备的消息。

需要明确的是,我不想在 fcm 消息中使用通知属性。我更喜欢数据属性,让移动开发人员能够自定义通知。

我们目前有以下设置

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  log('Got a message whilst in the Background!');
  log('Message data: ${message.data}');
  displayNotification();
}

Future<void> _firebaseMessagingForegroundHandler() async {
  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    log('Got a message whilst in the foreground!');
    log('Message data: ${message.data}');
    displayNotification();
  });
}
Run Code Online (Sandbox Code Playgroud)

以及以下内容:

Future<void> initFirebase() async {
  await Firebase.initializeApp();
  initFirebaseComponents();
}

void initFirebaseComponents() {
  _firebaseTokenRefreshHandler();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  _firebaseMessagingForegroundHandler();
}
Run Code Online (Sandbox Code Playgroud)

当Android设备位于前台时,通知会完美显示,当应用程序最小化时,通知也会完美显示在后台,但是当我们杀死应用程序时,通知将不再显示在后台。

我已经搜索过但没有找到解决方案,任何见解将不胜感激。

Vic*_*ele 4

由于您的有效负载是数据消息,因此设备似乎会忽略您的消息,因为数据消息被视为低优先级。

这是文档中的引用:

当您的应用程序处于后台或终止时,纯数据消息被设备视为低优先级,并将被忽略。但是,您可以通过在 FCM 负载上发送附加属性来显式提高优先级:

在 Android 上,将优先级字段设置为高。在 Apple(iOS 和 macOS)上,将 content-available 字段设置为 true。

这里的解决方案是在有效负载上设置附加属性。以下是文档中的示例有效负载,显示了如何发送附加属性。

{
  token: "device token",
  data: {
    hello: "world",
  },
  // Set Android priority to "high"
  android: {
    priority: "high",
  },
  // Add APNS (Apple) config
  apns: {
    payload: {
      aps: {
        contentAvailable: true,
      },
    },
    headers: {
      "apns-push-type": "background",
      "apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
      "apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
    },
  },
}
Run Code Online (Sandbox Code Playgroud)

注意:这只会提高消息的优先级,但不能保证传递。

更多信息