Search code examples
androidreact-nativefirebase-cloud-messaging

FCM data-only notifications are not shown when the app is closed (swiped)


I can get FCM data-only notifications to work in foreground and background, but not when the app is closed (swiped away) in Android (which I think would be the most common case).

I tried defining the priority to high in the payload, and I also changed the settings for the app not be battery optimized (just in case that was avoiding the background code that receives and processes the data notification from running). Nothing worked.

Is there a way to make it work when the app is closed? Otherwise I would need to make a notification + data message, but that would cause issues when the app is closed and in background: the icon would have a bad style (it's a small version of the launch icon in a white background), the messages won't be grouped, it would have no summary, etc...

I'm using react-native-firebase + notifee in an Expo managed app (submitted to the Play Store with EAS).

In the react-native-firebase docs linked above, there's a part with:

// Required for background/quit data-only messages on Android
priority: 'high',

But in my case I don't receive data-only messages when the app is in the quit state (even with a high priority defined), only when in background (minimized).


Solution

  • The reason was that I included messaging().setBackgroundMessageHandler(...) inside a useEffect() hook. It must be included outside any React component, because there will be no React component when the app is closed (but it seems that it's present when in background/minimized).

    This method must be called outside of your application lifecycle, e.g. alongside your AppRegistry.registerComponent() method call at the the entry point of your application code.

    https://rnfirebase.io/messaging/usage#background--quit-state-messages

    I also had to run in the callback some initialization steps that I do when the app is started normally, like mocking an Intl provider so that I have access (imperatively) to the intl object from react-intl and some other things I do, which had to be adapted because I can't call hooks in the callback.