问题描述
我正在尝试在后台应用程序时处理数据,这是我在客户端的代码:
Future<void> init({context}) async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(
onMessage: onMessage,onBackgroundMessage: myBackgroundMessageHandler,onLaunch: onLaunch,onResume: onResume,);
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
}
Future<dynamic> onResume(Map<String,dynamic> message) async {
App.isNewNotificationNotifier.value = true;
App.navKey.currentState.pushNamed("/Notifications");
print("appInBackground: $message");
}
Future<dynamic> onLaunch(Map<String,dynamic> message) async {
Timer.periodic(Duration(seconds: 1),(timer) {
if (App.isAppBuild) {
timer.cancel();
App.isNewNotificationNotifier.value = true;
App.navKey.currentState.pushNamed("/Notifications");
}
});
print("appTerminated: $message");
}
Future<dynamic> onMessage(Map<String,dynamic> message) async {
App.isNewNotificationNotifier.value = true;
print("appInForeground: $message");
}
Future<dynamic> myBackgroundMessageHandler(Map<String,dynamic> message) async {
print("data in background");
if (message.containsKey('data')) {
// Handle data message
final dynamic data = message['data'];
}
if (message.containsKey('notification')) {
// Handle notification message
final dynamic notification = message['notification'];
}
// Or do other work.
}
在服务器端,我用这个正文发送一个 HTTP POST 请求:
{
registration_ids: [ 'xxxxx','xxxxx',],notification: {
title: 'FCM Message',body: 'This is an FCM notification message!',click_action: "FLUTTER_NOTIFICATION_CLICK",},data: {
object: loggedInUser,"body" : "great match!","title" : "Portugal vs. Denmark","content_available" : true,"priority" : "high","sound": "default","time_to_live":"2419200"
},"priority": "high","time_to_live" : 60
}
在这个正文中,在所有情况下都会收到通知(应用程序在后台/前台并终止) 当应用程序在后台或终止时,如果按下通知,将根据应用程序状态调用 onResume 和 onLaunch。 但就我而言,即使用户没有点击通知,我也需要处理数据。 所以我已经为 POST 请求尝试了这个正文:
{
registration_ids: [ 'xxxxx',data: {
title: 'FCM Message',object: loggedInUser,"time_to_live" : 60
}
但是有了这个正文,通知不会出现,而是调用了 myBackgroundMessageHandler 方法。 所以我想要完成的是,无论何时收到通知,都应该调用 myBackgroundMessageHandler,并且通知也会出现。
此 answer 泛泛地讨论了 Firebase 消息传递。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)