【问题标题】:How to run a function when a notification is received with Firebase Messaging ^8.0.0-dev.8 in Flutter?如何在 Flutter 中使用 Firebase Messaging ^8.0.0-dev.8 收到通知时运行函数?
【发布时间】:2021-03-04 22:45:18
【问题描述】:

您好,我正在使用 Flutter 构建我的应用,我需要在收到新通知时显示警报。
我一直在使用firebase_messaging 7.0.3,但遇到onBackgroundMessage 的错误。一个快速的谷歌搜索帮助我发现我得到的错误还没有得到修复。然而,其中一位开发人员在 20 天前发布了关于修复该问题的新版本软件包的更新。
新版本删除了旧的 onMessage 处理程序并引入了新的处理程序。 现在他们有了返回流的新事件处理程序,但无法通过使用 .listen() 函数。每当我收到通知时,都会得到一个:D/FLTFireMsgReceiver(22032): broadcast received for message 打印在控制台中,但 .listen() 中的代码不会被执行。

Here 是 Firebase Flutter 上一篇文章的链接,该文章是使用新版本软件包的指南。 这是我的代码:

...
FirebaseMessaging.onMessage.listen((event) {
 // do something
});
FirebaseMessaging.onMessageOpenedApp.listen((event) {
 // do something
});
FirebaseMessaging.onBackgroundMessage((message) {
 // do something
 return;
 }
...

【问题讨论】:

  • 我也面临同样的问题,你能解决这个问题吗??
  • 我最终使用了firebase_messaging: ^7.0.3。我通过将Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) async {} 添加到文件顶部(在导入下)并设置onBackgroundMessage: myBackgroundMessageHandler 来修复我遇到的错误。它现在完美运行,我还没有遇到任何错误。

标签: firebase flutter push-notification firebase-cloud-messaging android-notifications


【解决方案1】:

我发现让事件触发的一个解决方案是始终调用:

await FirebaseMessaging.instance.getToken();

紧接着

await Firebase.initializeApp();

一旦我调用它,FirebaseMessaging.onMessage.listen 就会按预期捕获事件。

【讨论】:

  • 好像不需要awaitgetToken
  • 谢谢,经过几天的搜索,这是解决方案
  • FirebaseMessaging.onMessage.listen 是这个工作的关键,谢谢!
【解决方案2】:
  • 当我的应用程序处于打盹模式时,我收到了相同的日志,以获取具有高优先级的数据通知。 这是因为 firebase-messaging 插件中的一些问题。
  • Firebase_messaging 插件在内部使用 JobIntentService 来处理后台 fcm 通知
  • JobIntentService 在 Android O 或更高版本中有一个约束,当运行 Job 时,它将受标准 JobScheduler 策略的约束。当设备处于打盹模式时,作业不会立即运行。 (reference link)
  • firebase_messaging git 存储库中出现了同样的问题 (bug link)

解决方案

  • One Signal(另一个推送通知提供商)通过修改 JobIntentService 版本解决了这个问题。 (OneSignal Solution)
  • 在较高级别上,即使在 Android O 及更高版本中,它也会对高优先级 fcm 通知使用唤醒锁来运行服务。
  • 通过编辑相应的文件在您的 ide 中添加此 Pull Request 更改。

TL;DR

通过编辑相应的文件在您的 ide 中添加此 Pull Request 更改。 以高优先级发送数据通知。

FCM 负载:

{
"message": {
    "token": "fcm_client_token",
    "data": {
        "title": "Hello",
        "body": "Test Message"
    },
    "android": {
        "priority": "high"
    }
}

}

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2020-04-23
    • 2020-01-29
    • 2021-10-14
    • 1970-01-01
    • 2021-03-01
    • 2020-01-27
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多