无法在Flutter Firebase云消息传递中处理自定义通知

mxg2im7a  于 2022-12-24  发布在  Flutter
关注(0)|答案(1)|浏览(134)

我已经使用flutter_local_notification包创建了一个自定义通知,当我使用FCM发送通知时,两个通知在应用程序的前台和后台状态都可见。当我点击FCM生成的通知时,其工作正常,但当点击自定义后台通知时,我的应用程序启动,但无法运行我的逻辑,所以请帮助我处理后台自定义通知
点击后台自定义通知时,会显示以下信息
尝试启动重复的背景分离菌株。正在返回...

  1. class NotificationService {
  2. static final NotificationService _notificationService =
  3. NotificationService._private();
  4. NotificationService._private();
  5. factory NotificationService() => _notificationService;
  6. final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  7. FlutterLocalNotificationsPlugin();
  8. final AndroidNotificationChannel _androidChannel =
  9. const AndroidNotificationChannel(
  10. 'high_importance_channel', // id
  11. 'Notifications', // title
  12. description: 'important notification channel', // description
  13. importance: Importance.high,
  14. playSound: true);
  15. final AndroidInitializationSettings _initializationSettingsAndroid =
  16. const AndroidInitializationSettings(
  17. 'app_icon',
  18. );
  19. ///This functions initializes Flutterlocalnotificationplugin with required settings and channels
  20. initialize() async {
  21. AndroidFlutterLocalNotificationsPlugin? resp =
  22. flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
  23. AndroidFlutterLocalNotificationsPlugin>();
  24. await resp!.createNotificationChannel(_androidChannel);
  25. resp.requestPermission();
  26. var initializationSettings =
  27. InitializationSettings(android: _initializationSettingsAndroid);
  28. await flutterLocalNotificationsPlugin.initialize(initializationSettings,
  29. onDidReceiveNotificationResponse: _handleForegroundNotification,
  30. onDidReceiveBackgroundNotificationResponse:
  31. _handleBackgroundNotification);
  32. }
  33. /// This function create the custom notifcation.
  34. /// before calling this function , firebaseLocalNotification instance should be initialized
  35. showNotification(RemoteMessage message) {
  36. var initializationSettings =
  37. InitializationSettings(android: _initializationSettingsAndroid);
  38. flutterLocalNotificationsPlugin.initialize(initializationSettings,
  39. onDidReceiveNotificationResponse: _handleForegroundNotification,
  40. onDidReceiveBackgroundNotificationResponse:
  41. _handleBackgroundNotification);
  42. flutterLocalNotificationsPlugin.show(
  43. 1123,
  44. message.data['title'],
  45. message.data['body'],
  46. const NotificationDetails(
  47. android: AndroidNotificationDetails(
  48. '1123',
  49. 'channel.name',
  50. channelDescription: 'channel.description',
  51. color: Colors.blue,
  52. playSound: true,
  53. ),
  54. ));
  55. }
  56. }
  57. ///This functions handle background notification press and performs given instructions
  58. @pragma('vm:entry-point')
  59. _handleBackgroundNotification(NotificationResponse response) async {
  60. await Future.delayed(Duration(seconds: 3));
  61. Fluttertoast.showToast(
  62. msg: "backgrrrround call nice no",
  63. toastLength: Toast.LENGTH_SHORT,
  64. gravity: ToastGravity.CENTER,
  65. timeInSecForIosWeb: 1,
  66. backgroundColor: Colors.red,
  67. textColor: Colors.white,
  68. fontSize: 16.0);
  69. }
  70. ///This functions handel foregroud notification press and performs given instruction
  71. _handleForegroundNotification(NotificationResponse response) async {
  72. await Future.delayed(Duration(seconds: 3));
  73. Fluttertoast.showToast(
  74. msg: "Forerground call nice no",
  75. toastLength: Toast.LENGTH_SHORT,
  76. gravity: ToastGravity.CENTER,
  77. timeInSecForIosWeb: 1,
  78. backgroundColor: Colors.red,
  79. textColor: Colors.white,
  80. fontSize: 16.0);
  81. }

另一类用于管理FCM

  1. class FCMService {
  2. final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  3. String? fcmToken;
  4. ///This function initialized FCM and start stream of token,foregroundmessage,backgroundmessage
  5. initialize() async {
  6. fcmToken = await FirebaseMessaging.instance.getToken();
  7. await FirebaseMessaging.instance
  8. .setForegroundNotificationPresentationOptions(
  9. alert: true,
  10. badge: true,
  11. sound: true,
  12. );
  13. debugPrint(fcmToken);
  14. _listenToTokenStream();
  15. _listenToForegroundMessage();
  16. }
  17. // /Handle background but not teminated app notification press
  18. _listenToOnMessageOpenedApp() {
  19. //when
  20. FirebaseMessaging.onMessageOpenedApp.listen((message) {
  21. print("FCM>>>>>>>> backgroud");
  22. });
  23. }
  24. /// Request permission for higher sdk version
  25. _requestNotificationPermission() async {
  26. NotificationSettings settings = await _firebaseMessaging.requestPermission(
  27. alert: true,
  28. sound: true,
  29. );
  30. debugPrint('User granted permission: ${settings.authorizationStatus}');
  31. }
  32. /// listen to foreground message recieved from FCM
  33. _listenToForegroundMessage() {
  34. FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  35. NotificationService().showNotification(message);
  36. });
  37. }
  38. ///Listen to streamm of token when token expires helps us to updat it
  39. _listenToTokenStream() {
  40. FirebaseMessaging.instance.onTokenRefresh.listen((token) {
  41. fcmToken = token;
  42. debugPrint(fcmToken);
  43. }).onError((e) {
  44. debugPrint("token refresh failed");
  45. });
  46. }
  47. }
  48. ///listen background message recieve from FCM , DO NOT: perform heavy task in background
  49. ///otherwise your process may get killed
  50. Future<void> fcmBackgroundMessageHandler(RemoteMessage message) async {
  51. await Firebase.initializeApp();
  52. // await NotificationService().initialize();
  53. NotificationService().showNotification(message);
  54. }

主要方法:

  1. void main() async {
  2. WidgetsFlutterBinding.ensureInitialized();
  3. await Firebase.initializeApp();
  4. FCMService().initialize();
  5. NotificationService().initialize();
  6. FirebaseMessaging.onBackgroundMessage(fcmBackgroundMessageHandler);
  7. runApp(const MyApp());
  8. }
ff29svar

ff29svar1#

你应该在FCM初始化时监听后台消息,但是你是在main上做的,所以删除它并在FCM初始化中添加选项。
我已经更新了您的代码与所需的更新。

  1. void main() async {
  2. WidgetsFlutterBinding.ensureInitialized();
  3. await Firebase.initializeApp();
  4. FCMService().initialize();
  5. NotificationService().initialize();
  6. runApp(const MyApp());
  7. }
  8. /// fcm background message handler
  9. Future<void> fcmBackgroundMessageHandler(RemoteMessage message) async {
  10. print(message.notification!.title);
  11. // NotificationService().showNotification(message);
  12. }
  13. class FCMService {
  14. final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  15. String? fcmToken;
  16. ///This function initialized FCM and start stream of token,foregroundmessage,backgroundmessage
  17. initialize() async {
  18. fcmToken = await FirebaseMessaging.instance.getToken();
  19. await FirebaseMessaging.instance
  20. .setForegroundNotificationPresentationOptions(
  21. alert: true,
  22. badge: true,
  23. sound: true,
  24. );
  25. debugPrint(fcmToken);
  26. _listenToTokenStream();
  27. _listenToForegroundMessage();
  28. _listenToBackgroundMessage();
  29. }
  30. /// handle push notification events on background
  31. void handlePushNotificationBackgroundEvents() {
  32. FirebaseMessaging.onBackgroundMessage(fcmBackgroundMessageHandler);
  33. }
  34. // /Handle background but not teminated app notification press
  35. _listenToOnMessageOpenedApp() {
  36. //when
  37. FirebaseMessaging.onMessageOpenedApp.listen((message) {
  38. print("FCM>>>>>>>> backgroud");
  39. });
  40. }
  41. /// Request permission for higher sdk version
  42. _requestNotificationPermission() async {
  43. NotificationSettings settings = await _firebaseMessaging.requestPermission(
  44. alert: true,
  45. sound: true,
  46. );
  47. debugPrint('User granted permission: ${settings.authorizationStatus}');
  48. }
  49. /// listen to foreground message recieved from FCM
  50. _listenToForegroundMessage() {
  51. FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  52. NotificationService().showNotification(message);
  53. });
  54. }
  55. ///Listen to streamm of token when token expires helps us to updat it
  56. _listenToTokenStream() {
  57. FirebaseMessaging.instance.onTokenRefresh.listen((token) {
  58. fcmToken = token;
  59. debugPrint(fcmToken);
  60. }).onError((e) {
  61. debugPrint("token refresh failed");
  62. });
  63. }
  64. }
展开查看全部

相关问题