【问题标题】:How to receive custom data when app is terminated through push notification using firebase_messaging?当应用程序通过使用 firebase_messaging 的推送通知终止时如何接收自定义数据?
【发布时间】:2020-02-01 12:52:30
【问题描述】:

如标题所示,当用户在应用终止时单击通知时接收自定义数据的当前解决方法是什么?

似乎在 Android is not possible 上在 onLaunch 中接收数据消息(这是理想的方式) 在IOS上我还没有尝试过,因为我首先遇到了这个问题。

有什么线索吗?

附加信息:我通过firebase cloud function 发送的通知采用这种形式:

  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }
}

https://firebase.google.com/docs/cloud-messaging/concept-options

onResume 上我可以执行一个动作,但onLaunch 似乎没有被调用。

【问题讨论】:

  • 您可以尝试使用自定义 JSON Payloads

标签: flutter firebase-cloud-messaging


【解决方案1】:

我想,你已经获得了 onLaunch 的数据,只需要稍等片刻。我写它是因为我遇到了同样的事情。

你可以试试这个,

firebaseMessaging.configure(
  onMessage: (Map<String, dynamic> message) async { .. },
  onResume: (Map<String, dynamic> message) async { .. },
  onLaunch: (Map<String, dynamic> message) async {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Timer(const Duration(seconds: 7), () {
        // your process...
      });
    });
  },
);

在我的情况下,我也是这样使用的,并且解决了。

onLaunch: (Map<String, dynamic> message) async {
    WidgetsBinding.instance.addPostFrameCallback((ignored) {
      Timer.periodic(const Duration(seconds: 1), (timer) {
        if (CurrentUser.currentUser != null) {
          timer.cancel(); // important **
          // redirect process with post details inside data
          if (message['data']['type'] == NotifTypes.NEW_POST)
            goGroupAndPost(Map.from(message['data'])); 
        }
      });
    });
  },

【讨论】:

  • 在 firebase for flutter fcm 文档中说,当应用程序终止时,数据消息会被销毁f
【解决方案2】:

这是包含数据的有效负载应采用的格式。它确实有效,因为这就是我让它在我的项目中工作的方式。此外,为了让一切正常工作,answer here 可能对一般项目设置有帮助:

 {
      notification: {
        title: 'A title',
        body: 'The body.'
      },
      data: {
        // your data here
      },
      android: {
        ttl: 3600 * 1000,
        notification: {
          click_action: 'FLUTTER_NOTIFICATION_CLICK'
        }
      },
      // The below is for iOS specific properties
      // apns: {
      //   payload: {
      //     aps: {
      //       badge: 42
      //     }
      //   }
      // },
      tokens: [] // or a single 'token'
    }

【讨论】:

  • android 键应该做什么?
  • 有些特定的属性只与一个平台相关。 android 仅适用于 android 通知,而 apns 适用于 iOS。
【解决方案3】:

判断您的 Activity 是否在前台(并且反应不同)可能有点棘手。我最喜欢的方法是在 Activity 中注册一个本地 BroadcastReceiver,然后从服务中创建一个 sendBroadcast。如果您的接收器正在运行,您将从该方法中获得 true(意味着您的应用在前台,否则为 false

你可以看一个例子(使用GCM,但是FCM的逻辑是一样的)Source

这也是一个很好的例子MyFirebaseMessagingService

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2016-03-25
    • 2017-08-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多