简体   繁体   English

在 Flutter 中,我们如何使用 Firebase Messaging onBackgroundMessage 创建通知,使用 flutter_local_notifications?

[英]In Flutter, how do we use Firebase Messaging onBackgroundMessage to create a notification, using flutter_local_notifications?

We are working on an encrypted chat application where we use Firebase Messaging for data notifications.我们正在开发一个加密的聊天应用程序,我们使用 Firebase 消息发送数据通知。 Some client-side logic needs to be done upon receiving a data notification, before showing an actual notification to the user.在向用户显示实际通知之前,需要在收到数据通知后完成一些客户端逻辑。 For example, a phone number will have to be translated to a local contact name.例如,必须将电话号码转换为本地联系人姓名。 This translation is done by lookup with a map that is already available globally.这种转换是通过使用已经全球可用的地图进行查找来完成的。

The data notifications are received just fine and the onBackgroundMessage callback is called as well.数据通知接收得很好,并且 onBackgroundMessage 回调也被调用。 However, it seems impossible to access any kind of state from the onBackgroundMessage function.但是,似乎不可能从 onBackgroundMessage 函数访问任何类型的状态。 For example, printing the phone number of the logged in user returns null.例如,打印登录用户的电话号码返回 null。 Printing this same global variable from the onMessage callback works just fine.从 onMessage 回调打印这个相同的全局变量工作得很好。

Running flutter_local_notifications from onMessage works fine, but again, does not work at all from onBackgroundMessage as 'no implementation could be found for the method .show()'.从 onMessage 运行 flutter_local_notifications 工作正常,但同样,从 onBackgroundMessage 根本不起作用,因为“找不到方法 .show() 的实现”。 At the moment, it claims that flutterLocalNotificationsPlugin is null, which it isn't really.目前,它声称 flutterLocalNotificationsPlugin 为 null,但事实并非如此。

It seems to us that onBackgroundMessage has no access to anything the app provides, as soon as the app is backgrounded.在我们看来,只要应用程序处于后台, onBackgroundMessage 就无法访问应用程序提供的任何内容。 Something has to be done to make some of the scope/context available to the background process.必须做一些事情才能使某些范围/上下文可用于后台进程。 For now, that would mainly be the flutter_local_notifications plugin in its entirety, as well as the local contacts list to translate phone number to name.目前,这主要是整个 flutter_local_notifications 插件,以及将电话号码转换为姓名的本地联系人列表。

Has anyone got any idea how to do this?有没有人知道如何做到这一点?

Here is some of the code:这是一些代码:

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
final _chatRepository = ChatRepository();

Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) async {
  if(message.containsKey('data')) {
    await _showNotification(message);
    return Future<void>.value();
  }
}

Future _showNotification(message) async {
  List<String> numbers = [];
  numbers.add(message['data']['sender']);
  var name = await _chatRepository.translatePhoneNumbersToChatName(numbers);
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'channel id', 'channel name', 'channel description',
      importance: Importance.Max, priority: Priority.High);
  var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
  var platformChannelSpecifics = new NotificationDetails(
      androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
  await flutterLocalNotificationsPlugin.show(
    0,
    name,
    message['data']['body'],
    platformChannelSpecifics,
    payload: message['data']['body'],
  );
}

class NotificationHandler {
  final FirebaseMessaging fcm = FirebaseMessaging();
  StreamSubscription iosSubscription;
  String deviceToken = "";

  Future<void> initialize() async {
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onClickNotification);

    fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        if(message.containsKey('data')) {
          print(message);
          _showNotification(message);
        }
      },
      onBackgroundMessage: Platform.isIOS
          ? null
          : backgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        if(message.containsKey('data')) {
          print(message);
          _showNotification(message);
        }
      },
      onResume: (Map<String, dynamic> message) async {
        if(message.containsKey('data')) {
          print(message);
          _showNotification(message);
        }
      },
    );
    _updateDeviceToken();
  }
.
.
.

Of course, the initialize above is called early on in the application lifecycle.

class NotificationHandler {
  static final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // make it a static field of the class
  // ...
}

Future _showNotification(message) async {
  // ...
  await NotificationHandler.flutterLocalNotificationsPlugin.show( // access it
    // ...
  );
}

Hope this works for you.希望这对你有用。

This plugin explains it all better than I could, but it just so happens that the background is a completely different isolate/context and thus it has no access to any plugins if they use an old (pre Flutter 12) API.这个插件比我能更好地解释这一切,但碰巧背景是完全不同的隔离/上下文,因此如果它们使用旧的(Flutter 12 之前的)API,它无法访问任何插件。 https://pub.dev/packages/android_alarm_manager#flutter-android-embedding-v1 https://pub.dev/packages/android_alarm_manager#flutter-android-embedding-v1

Embedding v1 requires you to register any plugins that you want to access from the background.嵌入 v1 要求您注册要从后台访问的任何插件。 Doing this makes it flutter_local_notifications work properly.这样做会使 flutter_local_notifications 正常工作。

Unfortunately, FCM docs are heavily lacking.不幸的是,FCM 文档严重缺乏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 flutter 和 firebase (FCM) 中使用 onBackgroundMessage,onBackgroundMessage 没有被触发 - How to use onBackgroundMessage in flutter with firebase (FCM), The onBackgroundMessage is not getting triggered Flutter 通知与 Firebase 云消息传递 - Flutter Notifications with Firebase Cloud Messaging Flutter firebase 消息中的双重通知 - Double Notifications in Flutter firebase messaging Flutter firebase消息未收到通知 - Flutter firebase messaging not receiving notifications Flutter - Firebase 使用 firebase 消息传递成功但未收到通知的推送通知 - Flutter - Firebase push notification using firebase messaging success but not get notification 如何调试 iOS 未收到推送通知(使用 firebase_messaging 的 Flutter)? - How to debug iOS not receiving push notifications (Flutter using firebase_messaging)? Flutter:如何在 firebase_messaging package 中定义通知通道? - Flutter: How to define notification channel in firebase_messaging package? 颤动的firebase消息传递-ios静默通知未在后台启动应用程序以通过后台服务处理通知 - flutter firebase messaging - ios silent notifications not launching the app in background to process the notification through background service Flutter 中特定设备的 Firebase 消息通知 - Firebase Messaging notification for specific device in flutter Flutter Firebase 消息推送通知格式 3 行 - Flutter firebase messaging push notification format 3 lines
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM