Flutter App Firebase push notification not coming in background

851

Thank to all for your response.

I Found the solution that why my background handler not working because I am running my app in Debugging mode. As per the FlutterFire Cloud messaging Doc background method not work in Debugging mode if you kill your app.

You can test your background handler method by run your application in debug and then background it by switching apps so it's no longer in the foreground.

If You want to check After app terminate/kill from recent task then Run app in Release Mode. It Works fine

Again thanks to All.

Share:
851
sunil Kumawat
Author by

sunil Kumawat

Updated on January 03, 2023

Comments

  • sunil Kumawat
    sunil Kumawat over 1 year

    I am facing issue received notifications when app terminated/Remove from recent apps from background.

    I have complete all the setup required for android app in build.gradle files both app or project level. I am able to receive push notification when app is open or when app is in the recent apps.

    Library versions

    firebase_messaging: ^11.2.0
    firebase_core: ^1.10.0
    flutter_local_notifications: ^9.1.4
    

    here is my code.

    await Firebase.initializeApp();
    
        FirebaseMessaging messaging = FirebaseMessaging.instance;
    
        messaging.getToken().then((value) {
          print('firebase token =$value');    
        });
    
        FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
          //print(event.notification!.body);
          RemoteNotification? notification = message.notification;
          if (notification != null) {
            print("Notification received when app in foreground");
          }
        });
    
        FirebaseMessaging.onMessageOpenedApp.listen((message) {
          print('Message clicked!');
        });
    
        await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
          alert: true,
          badge: true,
          sound: true,
        );
    

    BackgroundMessage handler code is below

    Future<void> _messageHandler(RemoteMessage message) async {
      await Firebase.initializeApp();
      RemoteNotification? notification = message.notification;
      if (notification != null) {
        print("Notification received when app in background");
      }
    }
    

    Below is my complete code of main.dart file

    Future<void> _messageHandler(RemoteMessage message) async {
      await Firebase.initializeApp();
      RemoteNotification? notification = message.notification;
      if (notification != null) {
        print("Notification received when app in background");
      }
    }
    
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging.onBackgroundMessage(_messageHandler);
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      bool isUserLoggedIn = true;
      bool isLogoutAlertShown = false;
      final materialAppKey = GlobalKey();
      late FirebaseMessaging messaging;
    
    
      @override
      void initState() {
        super.initState();
        setUpNotification();
      }
    
      setUpNotification() async {
        messaging = FirebaseMessaging.instance;
        messaging.getToken().then((value) {
          print('firebase token =$value');
          //sendTokenToServer(value);
          Pref.setFcmToken(token: '$value');
        });
        FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
          //print(event.notification!.body);
          RemoteNotification? notification = message.notification;
          if (notification != null) {
            print("Notification received when app in foreground");
          }
        });
        FirebaseMessaging.onMessageOpenedApp.listen((message) {
          print('Message clicked!');
        });
       await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
          alert: true,
          badge: true,
          sound: true,
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return _materialApp();
      }
    
      Widget _materialApp() {
        return FutureBuilder(
            future: _loginState(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return MaterialApp(
                  debugShowCheckedModeBanner: false,
                  key: materialAppKey,
                  darkTheme: AppTheme.lightTheme,
                  theme: AppTheme.lightTheme,
                  home: isUserLoggedIn == true ? 
                  BottomNavigationContainer() : LoginOptions(),
                );
              } else {
                return Container(color: Colors.white);
              }
            });
      }
    
      Future<void> _loginState() async {
        final token = await Pref.getToken();
        isUserLoggedIn = token.length > 0 ? true : false;
      }
    }
    

    Suggest me what I am missing or doing wrong.

    • Yashraj
      Yashraj about 2 years
      Add main.dart file code.
    • sunil Kumawat
      sunil Kumawat about 2 years
      main.dart file code update @Yashraj
    • Yashraj
      Yashraj about 2 years
      Add this line in main() : FirebaseMessaging.onBackgroundMessage(_messageHandler);
    • sunil Kumawat
      sunil Kumawat about 2 years
      Added but still not working when i remove the app from recent app. @Yashraj
    • Martin Zeitler
      Martin Zeitler about 2 years
      At least on Android this requires an implementation of MessagingService ...which is white-listed, in order to be able to run in the background (even when Activity is not running). While I'd assume this to be a likely duplicate Q, without having searched ...the assumption, that an app which is not running, could handle a background message, makes no sense at all.
    • sunil Kumawat
      sunil Kumawat about 2 years
      Thank you for the response. Can you please suggest me how to implement this service. so i can receive notification in background when app is not running. @MartinZeitler
    • mario francois
      mario francois about 2 years
      Check the "developer options" in the "settings", then "Running services", then in the menu "show cached processes" and check if your app is there.
    • mario francois
      mario francois about 2 years
      If the processe is there, there is no problem. What are you doing in background? I just see a print. The print won't work when the app is close.
    • sunil Kumawat
      sunil Kumawat about 2 years
      thanks for your response. I check the settings also it's working. For background message we just need to add background method flutter automatically generate notification if we added this method. @mariofrancois
    • Hardik Mehta
      Hardik Mehta about 2 years
      Can you restart your android once and check again
    • sunil Kumawat
      sunil Kumawat about 2 years
      I Already checked this by restarting my android device.@HardikMehta
    • Yashraj
      Yashraj about 2 years
      Have you tried in another devices? Which device are you using?
    • sunil Kumawat
      sunil Kumawat about 2 years
      I have tried on 3 different device and versions. Redmi note 9 (Version 10),Redmi Note 8 (Version 11) and Oppo A5 (Version 9) @Yashraj
    • Yashraj
      Yashraj about 2 years
      So the issue maybe is in missing some configuration part. add your gradle files here.
    • BJW
      BJW about 2 years
      Did you try creating a NotificationChannel? Check this Medium post: rechor.medium.com/…
  • A.K.J.94
    A.K.J.94 about 2 years
    another way is open app again and close it, hence it will work as terminated app.
  • Md. Kamrul Amin
    Md. Kamrul Amin about 2 years
    I was wasting my time on debug mode. This answer should be the only answer regarding this problem. God Bless You!