简体   繁体   中英

FCM Notification not firing when app is killed

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

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.

When the App is killed the only way to "do something" when FCM wants to trigger some behaviour is by using a BroadcastReceiver: https://chloe-thhsu.medium.com/a-simple-way-to-combine-fcm-notification-with-tts-b48a777ec84f (you need only one piece of example code at this link)

FCM should trigger some Intent and only registered App will receive it and do something.

BroadcastReceivers works even when the App is closed/killed, but them allow only basic "actions" when them are triggered. For you it could be usable: " start and Activity using an Intent by passing XYZ argument " where your App/Activity will be launched and you can do "all what you want" from there.

You can trigger the notification onMessage function is by simply getting all the data in the data key instead of notification key. The data that is being send, please update the key from notification to data.

Handling FCM notifications in the background even when app is terminated has been there for quite some time now. The steps

  void _setupFCM() async {
    await Firebase.initializeApp();
    _messaging = FirebaseMessaging.instance;
    // The function passed here will be fired when app is in background and when app is terminated
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    FirebaseMessaging.onMessage.listen((event) {
    //...
    //...
    // This is fired when app is in foreground
    });
  }

Only thing to keep in mind is that the function passed for firing upon background has to be an anonymous function , that is it should be outside any class. The function will be executed in a separate isolate, so you can perform any kind of non tasks like network call, show a notification, update database etc (anything that does not involve UI). You can find more documentation here

EDIT- I may have misread the question a bit. The answer above is for times when you want to handle something when a notification is received. As for the notification, unless it is a data notification, a notification should pop up on its own. You can generate your own notification using something like flutter_local_notifications in the callback itself as well!

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

If you getting notification while in foreground and background state and not in terminated state it's may not only because of your code. If you are running in debug mode then try totally terminate the application and launch without through IDE, launch from mobile/simulator. Android OS will restrict background activity while debugging this may cause to avoid the notification from firebase.

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