'How to receive Firebase Notification in background using React Native Script

index.js:

   import bgNotification from './bgNotification'

   AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => 
   bgNotification);

build.gradle:

   implementation project(':react-native-firebase')
   implementation "com.google.android.gms:play-services-base:15.0.1"
   implementation "com.google.firebase:firebase-core:15.0.2"
   implementation "com.google.firebase:firebase-storage:15.0.2"
   implementation "com.google.firebase:firebase-messaging:15.0.2"
   implementation "com.google.firebase:firebase-auth:15.0.0"

bgNotification.js:

   import firebase from 'react-native-firebase';
   // Optional flow type
   import type { RemoteMessage } from 'react-native-firebase';

   export default async (message: RemoteMessage) => {
     return Promise.resolve();
   }

Please help me to find issue in above code. There is an other solutions that runs the app in background and complete required task when a notification is received.



Solution 1:[1]

I was having the same problem. I searched a lot about this problem, some suggested using headless js task. But I just added the following code in my index.js file and it worked for me :

import messaging from '@react-native-firebase/messaging';

messaging().setBackgroundMessageHandler(async remoteMessage => {
  console.log('Message handled in the background!', remoteMessage);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aditya Bhandari