androidflutterpush-notificationfirebase-cloud-messagingremote-notifications

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


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.


Solution

  • 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