简体   繁体   中英

firebaseMessagingBackgroundHandler not triggered when app is in background

I assumed I followed all the steps to handling background notifications from firebase in flutter. I have created a top-level function that I am expecting to be triggered whenever a notification comes in. However, the function is never triggered.

Here's the top-level background handler function that exists in my home page widget but outside the class:

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  // ignore: avoid_print
  print('A background message just showed up :  ${message.messageId}');

  // update SQLite
  var result = await PageService.instance
      .add(PageService.instance.convertToPage(message.data));
  print('added to db: ${result}');
}

Here is my home page init state that calls a function to initialize firebase messgaging:

@override
  void initState() {
    super.initState();

    _initializeFirebaseMessaging();
  }

And then here is the _initializeFirebaseMessaging function that is defined in the home page class as well:

void _initializeFirebaseMessaging() {
    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      print('new notification arrived');
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      // update SQLite
      var result = await PageService.instance
          .add(PageService.instance.convertToPage(message.data));
      print('added to db: ${result}');

      if (notification != null && android != null) {
        // show notification
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                color: Colors.blue,
                playSound: true,
                icon: '@mipmap/ic_launcher',
              ),
            ));
      }
    });
  }

The onmessage.listen works fine as I get notificationd and handle them while I'm in the app, but the background handler is not triggered at all.

I would appreciate any help!

You have to call FirebaseMessaging.onBackgroundMessage inside your main() not in initState()

try: after main func

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  ...
}

and remove WidgetsFlutterBinding.ensureInitialized(); in firebaseMessagingBackgroundHandler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM