首页 > 解决方案 > Flutter Firebase 云消息传递:`onBackgroundMessage` 的用途是什么?

问题描述

我用推送通知设置了我的颤振应用程序,但我不知道以下代码的用途是什么:

  _initiateFcm() async {
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  }

  Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    await Firebase.initializeApp();
    print('A bg message just showed up: ${message.messageId}');
  }

除了初始化firebase应用程序之外,我没有找到将它用于其他任何用途的示例......我的main()方法中已经发生了什么。这样做的目的是什么?什么时候应该使用它?

我有这些功能,我实际处理我收到的推送通知:

FirebaseMessaging.onMessage.listen((RemoteMessage message) {});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {});

但我什么都不用onBackgroundMessage...

文档说:

  /// Set a message handler function which is called when the app is in the
  /// background or terminated.
  ///
  /// This provided handler must be a top-level function and cannot be
  /// anonymous otherwise an [ArgumentError] will be thrown.

但是没有人在我检查的任何地方使用这种方法......

标签: firebaseflutterdartpush-notification

解决方案


FirebaseMessaging.onBackgroundMessage()

当应用程序未运行(应用程序在后台)时收到您的通知时,将调用此函数。

所以,当收到后台通知时,如果你有想要做的事情,你可以使用这个功能。

您可以使用该功能执行诸如 HTTP 请求、IO 操作(更新本地存储)等逻辑,当您在应用程序未运行时收到通知时与其他插件通信。

注意:无法从该函数更新应用程序状态或执行任何影响 UI 的逻辑(因为处理程序在应用程序上下文之外在其自己的隔离中运行)。

更多信息


推荐阅读