FCM Notification not firing when app is killed

2,995

Solution 1

Looks like you're calling the FirebaseMessaging.onBackgroundMessage() method inside initState() of a stateful widget which is not allowed as it is stated in the documentation:

Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can however perform logic such as HTTP requests, IO operations (updating local storage), communicate with other plugins etc.

You should set the background messaging handler before runApp():

/// Define a top-level named handler which background/terminated messages will
/// call.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Firebase App
  await Firebase.initializeApp();

  // Set the background messaging handler early on, as a named top-level function
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  // Run your app
  runApp(HomeScreen());
}

Check this for details.

Solution 2

I recommend you to use OneSignal for push notifications. It is more stable and always receive notifications. (Even when the app is killed).

Share:
2,995
mcfred
Author by

mcfred

A curious mindset and a solid hunger to learn more each day.

Updated on December 20, 2022

Comments

  • mcfred
    mcfred over 1 year

    FCM notifications work for me when the app is in background or in foreground but not when the app is killed.

    Here's my FCM configuration code:

     Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      await Firebase.initializeApp();
      print("Handling a background message: ${message.messageId}");
    }
    class CategoriesScreen extends StatefulWidget {
      static const routeName = '/view-cateogries';
      _CategoriesScreenState createState() => _CategoriesScreenState();
    }
    
    class _CategoriesScreenState extends State<CategoriesScreen> {
      Future _screenFuture;
      void initState() {
        _saveDeviceToken(FirebaseMessaging.instance);
         FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
        super.initState();
      }
    

    I have read numeruos articles online and here on stackoverflow. For instance, one of the suggestions was to disable battery saver. I have tried that but no luck. Any ideas what I am missing?

    I am using firebase-messaging version ^10.0.2

    • DarShan
      DarShan almost 3 years
      Looks like you are still using the older version, start by migrating & follow this guide for background handling: firebase.flutter.dev/docs/messaging/usage/#background-messag‌​es
    • mcfred
      mcfred almost 3 years
      @DarShan, what do I need to migrate to?
    • Sanket Vekariya
      Sanket Vekariya almost 3 years
      Is this only with Android or IOS too?
    • mcfred
      mcfred almost 3 years
      Android for now but in the future, I will face the same issue with ios am sure.
    • Robin Dijkhof
      Robin Dijkhof almost 3 years
      This is simply not possible
    • mcfred
      mcfred almost 3 years
      @RobinDijkhof, why is not possible?
    • Samin
      Samin almost 3 years
      Did you prioritize the FCM JSON Request ? Because I'm able to get FCM, even app is killed (swipe away from recent screen) on Android and IOS also. I'm using data notification, and I got the response on the android. For IOS, it's a bit tricky
  • mcfred
    mcfred almost 3 years
    I have tried this but it doesn't trigger the notification. I changed notification to data, ran firebase deploy, restarted my app and tried it but no luck.
  • mcfred
    mcfred almost 3 years
    your assumption is correct. I do want to handle notifications when the app is in foreground, background and killed. I tried to follow your instructions and created a function outside class and referenced it inside the class but I still do not get notification when the app is killed. I have installed the app in two phones. The app with admin login is supposed to receive the notification. It gets notified when an order is created while in foreground and background, but not when the app is killed. Please see my updated code.
  • Chinmay Kabi
    Chinmay Kabi almost 3 years
    Can you say what version of firebase_messaging you're using
  • mcfred
    mcfred almost 3 years
    This is what I am using: firebase_messaging: '>=0.0.7 <9.1.0'
  • Chinmay Kabi
    Chinmay Kabi almost 3 years
    I think you should update it to the latest and try, firebase_messaging: ^10.0.2. Even the syntax has changed because fcm.configure() had some issues
  • mcfred
    mcfred almost 3 years
    I did that but still no notification when app is killed. Please see my code.