Методы Flutter onSelectNotification в flutter_local_notifications не работают - PullRequest
1 голос
/ 06 мая 2020

Я пытаюсь обрабатывать сообщения FCM в своем приложении, когда оно находится в фоновом режиме. Я использую для этого сообщения данных, обрабатываю их в глобальной функции myBackgroundMessageHandler и создаю локальное уведомление с помощью плагина flutter_local_notifications, и я получаю и показываю пользователю событие уведомления pu sh, если процесс приложения был убит. Но я не могу поймать событие, когда пользователь открывает приложение через это уведомление pu sh. Вот моя инициализация fcm:

   void initFirebasePushNotifications(){
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        Fluttertoast.showToast(msg: "onMessage $message");
//        _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        Fluttertoast.showToast(msg: "onLaunch $message");
//        _navigateToItemDetail(message);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        Fluttertoast.showToast(msg: "onResume $message");
//        _navigateToItemDetail(message);
      },
    );
    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(
            sound: true, badge: true, alert: true, provisional: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      pushNotificationManager.subscribe(MyApp.user);
      print("Push Messaging token: $token");
    });
  }

и myBackgroundMessageHandler:

import 'dart:io';
import 'dart:math';

import 'package:didiservicekiosk/ui/main/main_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';

// Streams are created so that app can respond to notification-related events since the plugin is initialised in the `main` function
final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject =
BehaviorSubject<ReceivedNotification>();

final BehaviorSubject<String> selectNotificationSubject =
BehaviorSubject<String>();

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
  print('AppPushs myBackgroundMessageHandler : $message');
  _showNotification(message);
  return Future<void>.value();
}

Future _showNotification(Map<String, dynamic> message) async {
  var pushTitle;
  var pushText;
  var action;

  if (Platform.isAndroid) {
    var nodeData = message['data'];
    var notification = message['notification'];
    pushTitle = nodeData['title'];
    pushText = nodeData['body'];
    action = nodeData['action'];
  } else {
    pushTitle = message['title'];
    pushText = message['body'];
    action = message['action'];
  }
  print("AppPushs params pushTitle : $pushTitle");
  print("AppPushs params pushText : $pushText");
  print("AppPushs params pushAction : $action");
  var initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/launcher_icon');
  var initializationSettingsIOS = IOSInitializationSettings(onDidReceiveLocalNotification:
      (int id, String title, String body, String payload) async {
    print("onDidReceiveLocalNotification");
    didReceiveLocalNotificationSubject.add(ReceivedNotification(
        id: id, title: title, body: body, payload: payload));
  });
  var initializationSettings = InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);

// @formatter:off
  var platformChannelSpecificsAndroid = new AndroidNotificationDetails(
      '234', 'Chat notifications', 'Notifications from chat',
      playSound: true,
      enableVibration: true,
      importance: Importance.Max,
      priority: Priority.High);
// @formatter:on
  var platformChannelSpecificsIos =
      new IOSNotificationDetails(presentSound: false);
  var platformChannelSpecifics = new NotificationDetails(
      platformChannelSpecificsAndroid, platformChannelSpecificsIos);
  FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  await _flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: selectNotification);

new Future.delayed(Duration.zero, () {
    _flutterLocalNotificationsPlugin.show(
      Random().nextInt(1000),
      pushTitle,
      pushText,
      platformChannelSpecifics,
      payload: 'No_Sound',
    );
  });
}

Future selectNotification(String payload) async {
//  if (payload != null) {
    print('selectNotification notification payload: ' + payload);
//  }
}

class ReceivedNotification {
  final int id;
  final String title;
  final String body;
  final String payload;

  ReceivedNotification({
    @required this.id,
    @required this.title,
    @required this.body,
    @required this.payload,
  });
}

Есть предложения?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...