【问题标题】:setBackgroundMessageHandler is not called in terminated statesetBackgroundMessageHandler 未在终止状态下调用
【发布时间】:2026-01-26 23:20:05
【问题描述】:

我在我的 react-native 应用程序中使用 firebase/messaging 来接收来自 firebase 的纯数据通知。

收到消息后,我将处理数据,更新我的状态,并在应用程序处于后台或终止时显示带有 react-native-push-notification 的本地通知。

messaging().setBackgroundMessageHandler(async remoteMessage => {
  PushNotification.localNotification({...})
})

在 android 设备上,一切都在前台、后台和终止状态下完美运行。

在 iOS 前台和后台工作。

当应用程序终止时,我可以在控制台中记录通知(见下文)并且会有通知声音。但是没有显示本地通知。

当我尝试登录 iOS 设备时,控制台会打印以下输出

default 03:51:53.697535+0100 dasd Daemon Canceling Activities: {(
    com.apple.pushLaunch.de.myapp.app:D1FAA2
)}
default 03:51:53.697770+0100 dasd CANCELED: com.apple.pushLaunch.de.myapp.app:D1FAA2 at priority 10 <private>!

我来自服务器的消息是:

const message = {
      data: {
        body: JSON.stringify(msgBody),
        title: title,
      },
      contentAvailable: true,
      priority: "high",
      android: {
        priority: "high",
      },
      apns: {
        headers: {
          "apns-priority": "10",
          "apns-push-type": "alert", //already tried background too
          "apns-topic": "de.myapp.app",
        },
        payload: { aps: { sound: "default", contentAvailable: true } },
      },
 
      tokens: userTokens,
    };

这几天让我发疯,我无法让它工作。 感谢您的每一次帮助

【问题讨论】:

  • 最近我在我的一个应用程序中遇到了这个问题,并且能够通过使用多个包来修复它(经过大量的试验和错误)。我用"@react-native-community/push-notification-ios": "^1.4.1", "@react-native-firebase/app": "^8.4.3", "@react-native-firebase/messaging": "^7.8.4"
  • 你怎么能解决它?并且您现在能够解决处于终止状态的消息吗?
  • 在后台和终止状态下,通知由 iOS 处理。在前台,我使用了本地通知。前台 messaging().onMessage 处理程序和后台 messaging().setBackgroundMessageHandler 正在执行。
  • 消息格式为,{"notification": { "body": "", "title": "" },"content_available": true,"data": { ... },"priority": 10}
  • 所以你正在发送通知消息,对吧?因为我需要一个纯数据消息的解决方案

标签: firebase react-native push-notification firebase-cloud-messaging


【解决方案1】:

找到了!

Version 7.18.0 - August 13, 2020 Cloud Messaging
Deprecated setBackgroundMessageHandler. Use the new API onBackgroundMessage instead.

https://firebase.google.com/support/release-notes/js#cloud-messaging_2

【讨论】:

  • 它给出的错误未定义不是一个函数
【解决方案2】:

查看他们的文档,他们提到系统在某些条件下有意保留,不仅限于...

  • 当系统收到新的后台通知时,它会丢弃 较旧的通知,仅包含最新的通知。

  • 如果有东西强制退出或杀死应用程序,系统会丢弃
    举行通知。

  • 如果用户启动应用程序,系统会立即交付
    举行通知。

https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app

【讨论】:

  • 但是如果应用程序终止,Facebook 等应用程序如何仍然发送推送通知