【问题标题】:In Flutter Is that possible to call API request in firebase Messaging BackgroundHandler?在 Flutter 中是否可以在 firebase Messaging BackgroundHandler 中调用 API 请求?
【发布时间】:2023-02-01 18:01:29
【问题描述】:

我已经实现了聊天消息应用程序,用户可以在其中 从推送回复聊天 应用程序被杀死/背景/前景时的通知。 但是当应用程序处于终止状态时,API 调用不起作用 firebaseMessagingBackgroundHandler。 它停留在 sendNotification 函数上。

处理后台事件的代码:

 Future<void> 
 firebaseMessagingBackgroundHandler(RemoteMessage message) 
 async {
    await GetStorage.init();
    await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform);
    //Call HTTP request <Stuck here
    sendNotification(
      personUid,
      title,
      body,
      notificationTypeId,
      chatRoomId,
      userTokenDummy,
      userToken,
      serverKey,
      currentUserId,
      currentUserToken,
    );
  }

下面是 API 请求的代码:

  sendNotification({
    required String personUid,
    required String title,
    required String body,
    required int notificationTypeId,
    String? chatRoomId,
    String? userTokenDummy,
    String? userToken,
    String? serverKey,
    String? currentUserId,
    String? currentUserToken,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('https://fcm.googleapis.com/fcm/send'),
        headers: <String, String>{
          HttpHeaders.contentTypeHeader: 
  'application/json',
          HttpHeaders.authorizationHeader: 'key=$serverKey'
        },
        body: jsonEncode(
          <String, dynamic>{
            "data": <String, dynamic>{
              "title": title,
              "body": body,
              "click_action": "FLUTTER_NOTIFICATION_CLICK",
              "id": "1",
              "status": "done",
              "senderId": currentUserId,
              "senderToken": currentUserToken,
              "notificationTypeId": notificationTypeId,
              "chatRoomId": chatRoomId,
            },
            "android": {
              "priority": "high",
            },
            "apns": {
              "headers": {"apns-priority": "10"}
            },
            "to": userToken,
            "content_available": true,
            "mutable-content": 1,
            "priority": "high",
          },
        ),
      );

      return response;
    } catch (e) {
      console(e.toString());
    }
  }

【问题讨论】:

  • 也许你可以试试看它是否有效,如果它不分享你的调试细节?
  • 是的,我试过了,但没有用。它只是停留在 http 请求调用上。
  • 你的问题应该解释你做了什么,什么没有按你期望的方式工作。问“是否可能”并不能真正帮助我们理解问题所在。
  • 是的,当然。让我在这里分享一些代码。

标签: flutter firebase dart firebase-cloud-messaging


【解决方案1】:

是的,你可以在 firebaseMessagingBackgroundHandler 中调用 Http 请求。但请确保此 api 不会花费太多时间。因为长时间和密集的任务会影响设备性能。还要确保 api 中没有导致设备冻结的异常或错误。

为确保 api 不会永远运行,请在 http 类中设置超时。

有关更多信息,请参阅 firebase 文档:https://firebase.google.com/docs/cloud-messaging/flutter/receive

【讨论】:

  • 在我的例子中,API 调用没有执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2018-06-17
相关资源
最近更新 更多