【问题标题】:Flutter Firebase Messaging trigger onLaunchFlutter Firebase 消息触发 onLaunch
【发布时间】:2021-04-18 14:01:32
【问题描述】:

所以我有一个问题,因为我没有完全理解一些东西。所以我写了一个简单的应用程序来尝试一些东西,所以我通过 Firebase Cloud Messaging 从 Firebase 发送了一条消息。我使用 firebase_messaging 颤振插件(7.0.3 版)。它只是做一件简单的事情来获取消息并导航到另一个页面。我的问题是以下问题,onMessage 和 onResume 功能完美运行,但是当应用程序终止并且我单击应用程序打开的通知时,但没有任何反应。所以我阅读了文档,发现了这个 第三行说,数据丢失了……这是否意味着我丢失了有效负载中的所有数据? 如果有帮助,我的代码就在这里

 static final NavigationService _navigationService =
      loc.Locator.locator<NavigationService>();
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  Future<void> reqPermission() async {
    bool permission = true;
    if (Platform.isIOS) {
      permission = await _firebaseMessaging.requestNotificationPermissions();
    }
    if (permission) {
      _firebaseMessaging.configure(
        onMessage: (Map<String, dynamic> message) async {
          print(message);
          await _navigationService.navigateTo(NewPage.routeName);
        },
        onLaunch: (Map<String, dynamic> message) async {
          print('onLaunch $message');
          await _navigationService.navigateTo(NewPage.routeName);
        },
        onResume: (Map<String, dynamic> message) async {
          print('onResume $message');
          await _navigationService.navigateTo(NewPage.routeName);
        },
        onBackgroundMessage: _myBackgroundHandler,
      );
    }
  }

【问题讨论】:

    标签: flutter firebase-cloud-messaging


    【解决方案1】:

    我最近在 GitHub 上问过这个问题,见:https://github.com/FirebaseExtended/flutterfire/issues/5098#issuecomment-783444919

    旧版本确实如此,它需要本地解决方法。最新的非 nullsafety 版本 firebase_messaging: ^8.0.0-dev.14 将在终止状态下工作(除非您在 android 上强制退出应用程序)。更新的文档位于https://firebase.flutter.dev/docs/messaging/usage#receiving-messages

    【讨论】:

      【解决方案2】:

      您可以使用 fcm 发送通知和数据,它支持终止通知但不支持数据。您可以在通知中发送正文和标题,因此如果您需要基本通知(只有标题和正文)。您可以使用通知发送它。 如果您需要更多,可以将它与 flutter_local_notifications 包一起使用 在启动时。 https://pub.dev/packages/flutter_local_notifications

      这是令牌的使用方法

      _firebaseMessaging.onTokenRefresh.listen((newToken) {
            User _currentUser = FirebaseAuth.instance.currentUser;
            FirebaseFirestore.instance
                .doc("tokens/" + _currentUser.uid)
                .set({"token": newToken});
          });
      

      你可以这样推动它。

        Future<bool> sendNotification(
            {@required Map<String, dynamic> messageMap,
            @required AppUser appUser,
            @required String token}) async {
          String url = "https://fcm.googleapis.com/fcm/send";
          String _firebaseKey ="<your key>"
      
          Map<String, String> headers = {
            "Content-type": "application/json",
            "Authorization": "key=$_firebaseKey"
          };
          String json =
              '{ "to" : "$token", "data" : { "message" : "${messageMap["message"]}", "sendBy": "${appUser.name}", "messageType": "${messageMap["messageType"]}", "sendById" : "${appUser.userId}" } }';
          http.post(url, headers: headers, body: json);
          return true;
        }
      

      FCM 配置

      _firebaseMessaging.configure(
            onMessage: (Map<String, dynamic> message) async {
              print("onMessage: $message");
              //getNotificationMessage(message["data"]["message"]);
              if(message["data"]["messageType"]=="text"){
                NotificationHandler.showNotification(message); // Flutter Local Notification method
              } else{
                NotificationHandler.showBigPictureNotification(message);// Flutter Local Notification method
              }
            },
            onLaunch: (Map<String, dynamic> message) async {
              print("onLaunch: $message");
              if(message["data"]["messageType"]=="text"){
                NotificationHandler.showNotification(message);// Flutter Local Notification method
              } else{
                NotificationHandler.showBigPictureNotification(message);// Flutter Local Notification method
              }
            },
            onResume: (Map<String, dynamic> message) async {
              if(message["data"]["messageType"]=="text"){
                NotificationHandler.showNotification(message);// Flutter Local Notification method
              } else{
                NotificationHandler.showBigPictureNotification(message);// Flutter Local Notification method
              }
            },
            onBackgroundMessage: myBackgroundMessageHandler,
          );
        }
      

      这是后台消息处理程序

      Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) async {
        if (message.containsKey('data')) {
          // Handle data message
          final dynamic data = message['data'];
          if(message["data"]["messageType"]=="text"){
            NotificationHandler.showNotification(message);// Flutter Local Notification method
          } else{
            NotificationHandler.showBigPictureNotification(message);// Flutter Local Notification method
          }
      
        }
      
        return Future.value();
      }
      

      这就是我在项目中的做法

      【讨论】:

      • 我想在数据部分发送路线的名称。这可能吗?
      • @Butch 有可能。我在答案中添加了示例。也许会为你工作
      猜你喜欢
      • 2020-05-05
      • 2021-06-04
      • 2020-06-21
      • 2021-01-06
      • 2021-06-08
      • 2018-11-29
      • 2021-03-31
      • 2021-07-09
      • 2016-10-09
      相关资源
      最近更新 更多