Firebase push notifications callback doesn't work when app is terminated
B

3

6

So I updated the firebase_messaging and I had to change my code because FirebaseMessagin.configure() is deprecated and now when I receive the notification and click on the notification it doesn't open another screen.

This is how I implemented the notifications:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print('Handling a background message ${message.messageId}');
}
const AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  'This channel is used for important notifications.', // description
  importance: Importance.high,
);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'e-Rădăuți',
      debugShowCheckedModeBanner: false,
      initialRoute: '/',
      routes: {
        '/': (_) => MenuScreen(),
        '/events': (BuildContext context) => EventsScreen(),
      },
    );
  }
}
class MenuScreen extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

 Widget build(BuildContext context) {
    return Scaffold();
  }

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channel.description,
                icon: 'launch_background',
              ),
            ));
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      debugPrint('A new onMessageOpenedApp event was published!');
      
      Navigator.pushNamed(context, '/events');
    });
  }
}

But .onMessageOpenedApp isn't called when I click on the notification because I don't get that debugPrint message in my console (VSCode) and I get the following errors:

D/FLTFireMsgReceiver( 4799): broadcast received for message
W/civic.e_radaut( 4799): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist,test-api, reflection, allowed)
W/civic.e_radaut( 4799): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist,test-api, reflection, allowed)
W/civic.e_radaut( 4799): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
W/civic.e_radaut( 4799): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
W/FirebaseMessaging( 4799): Notification Channel set in AndroidManifest.xml has not been created by the app. Default value will be used.
I/flutter ( 4799): Handling a background message 0:1617783965733220%2ebdcc762ebdcc76

I sent my notification from the firebase with the click_action: FLUTTER_NOTIFICATION_CLICK and in my manifest I've added

<intent-filter>
 <action android:name="FLUTTER_NOTIFICATION_CLICK" />
 <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

My firebase_messaging version is ^8.0.0-dev.15

So I don't know what I've missed or why it's not working. If you need more details please feel free to ask.

Bulrush answered 7/4, 2021 at 8:45 Comment(8)
hi, i have the same problem with firebasemessaging ^9.1.3, FirebaseMessaging.onMessageOpenedApp.listen is not triggered when notificacion is tapped and app is on foreground. did you found any solution?Rockefeller
@ALEXANDERLOZANO sorry for the late reply.. I think that if the app is in the foreground you should use .onMessage.listen' because the app is already opened and in foreground so you actually don't open the app so FirebaseMessaging.onMessageOpenedApp.listen` is not called but instead is called FirebaseMessaging.onMessage.listen. I'm not sure if this will work because I didn't implement an call back when the app is in the foreground. If you didn't find a solution message me and I'll try to implement in my code and see if it will workBulrush
thank you for your answer, i use: FirebaseMessaging.onMessage.listen((RemoteMessage message) { print("new message"); }); with not luck. notification arrive but listen is not triggeredRockefeller
I added a debugPrint(); in .onMessage and it's triggered if the app is in foreground but not when I click on it, it's triggered when I receive the notification. If I find a solution I'll tell youBulrush
@ALEXANDERLOZANO So it seems that you have to add local push notifications and work with that to make the callback when the app is in foreground.. I'll make a demo app tomorrow.. it's 1:40 AM :(Bulrush
@ALEXANDERLOZANO here is the demo app that I created github.com/SK1n/flutter_notifications_example . Hope it helpsBulrush
thanks a lot for your help, still not luck, as i need firebase_messaging firebasemessaging ^9.1.3, the notification click is not working in foreground, but, let me invite you a cup of coffeeRockefeller
Yeah sure, maybe I can help you. I mean I can't see your code so it is kind of hard to helpBulrush
B
17

I resolved this by using the .getInitialMessage() function (This is the callback if the app is terminated. My notifications worked when the app was on background but not terminated.

To resolve this I just added this to my code:

FirebaseMessaging.instance
    .getInitialMessage()
    .then((RemoteMessage message) {
  if (message != null) {
    Navigator.pushNamed(context, message.data['view']);
  }
});

I've made a working demo here

Bulrush answered 1/5, 2021 at 12:54 Comment(3)
Thank you! I tried your code and it works.Nadda
Finally! Thanks! <3Wray
How to make Android works on terminated firebase notifications?Endmost
C
1

It should work when the app is in the background, but when it is terminated you should use getInitialMessage.

onMessageOpenedApp: A Stream event will be sent if the app has opened from a background state (not terminated).

If your app is opened via a notification whilst the app is terminated, see getInitialMessage.

Check out the example: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_messaging/firebase_messaging/example/lib/main.dart#L116

Creighton answered 28/4, 2021 at 7:51 Comment(0)
N
1

if you want go to any page or lunch link when click notification before app started then you must use

getInitialMessage()

example:

FirebaseMessaging.instance
    .getInitialMessage()
    .then((RemoteMessage message) {
  if (message != null) {

   //to do your operation
   launch('https://google.com');

  }
});
Nomadize answered 7/8, 2021 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.