4

I am trying to send push notifications using react-native-firebase through firebase console when my app is closed or in the background, the notifications are received and shown as a pop-up but if my app is in the foreground the notifications are not appearing

I have been trying to do some code in on notification method as suggested in the docs but it's not working

please suggest something that my app can show notifications in foreground

Fariha Khalid
  • 91
  • 1
  • 6

3 Answers3

1

Please refer following link.

https://rnfirebase.io/docs/v5.x.x/messaging/android#(Optional)-Background-Messages

If you added, remove following line from your AndroidManifest.xml.

 <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
Nagesh Fultambkar
  • 546
  • 1
  • 7
  • 22
0

create a new notifactionHandler.js and import the code below.

import firebase from 'react-native-firebase';

exports.setNotificationListener = () => {
  return new Promise((resolve, reject) => {
    // triggers when notifiaction received while app on foreground
    this.notificationListener = firebase.notifications().onNotification((notification) => { 
      console.log(notification.data);
        setNotification({notification})
    });
    resolve(true);
  })
};

const setNotification = ({notification}) => {
  firebase.notifications().displayNotification(notification);
}

then import it on your splash or main page. then call setNotificationListener function. basicly firebase.notifications().onNotification catches notifications while app on foreground, and displays it with firebase.notifications().displayNotification

Arenak
  • 41
  • 3
0

in my case:

import firebase from 'firebase';
import * as Notice from "react-native-firebase";

componentDidMount() {
const firebaseConfig = {
  apiKey: "**********",
  authDomain: "**********",
  databaseURL: "**********",
  projectId: "**********",
  storageBucket: "**********",
  messagingSenderId: "**********",
  appId: "**********"
};
this.mNotifiConfig()
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
}



mNotifiConfig = async() => {
    Notice.messaging().hasPermission()
      .then(enabled => {
        console.log('HAS PERMISS: ', enabled)
        if (enabled) {
          Notice.messaging().getToken().then(token => {
            console.log("LOG: ", token);
          }).catch(err=> console.log(err))
        } else {
          Notice.messaging().requestPermission()
        }
      });
    const notificationOpen = await Notice
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      const action = notificationOpen.action;
      const notification = notificationOpen.notification;
      var seen = [];
      // this.onActionWithNotification(notification)
      console.log('NOTIFICATION IS OPNE')
    }
     // config android
    const channel = new Notice.notifications.Android.Channel(
      "test-channel",
      "Test Channel",
      Notice.notifications.Android.Importance.Max
    ).setDescription("My apps test channel");

// Create the channel
Notice.notifications().android.createChannel(channel);
this.notificationDisplayedListener = Notice
  .notifications()
  .onNotificationDisplayed((notification: Notification) => {
  console.log('CREATED CHANNEL')
    // Process your notification as required
    // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
  });

this.notificationListener = Notice
  .notifications()
  .onNotification((notification: Notification) => {
    console.log('HAS Notification: ', notification)
    // Process your notification as required
    // notification.android
    //   .setChannelId("test-channel")
    //   .android.setSmallIcon("ic_launcher");
    // firebase.notifications().displayNotification(notification).catch(err => console.error(err));

  let notification_to_be_displayed = new Notice.notifications.Notification({
    data: notification.data,
    sound: 'default',
    show_in_foreground: true,
    title: notification.title,
    body: notification.body,
  });
  if(Platform.OS == "android") {
    notification_to_be_displayed
    .android.setPriority(Notice.notifications.Android.Priority.High)
    .android.setChannelId("test-channel")
    .android.setSmallIcon("ic_launcher")
    .android.setVibrate(1000);
}
Notice.notifications().displayNotification(notification_to_be_displayed);
});

this.notificationOpenedListener = Notice
  .notifications()
  .onNotificationOpened((notificationOpen) => {
    // Get the action triggered by the notification being opened
    const action = notificationOpen.action;
    // Get information about the notification that was opened
    const notification = notificationOpen.notification;
    var seen = [];
    console.log('notification Day nay', notification)
    Notice
      .notifications()
      .removeDeliveredNotification(notification.notificationId);
    // this.onLinkingtoApp()
  });

  this.onMessageListener = Notice.messaging().onMessage((message: RemoteMessage) => {
    const {data} = message
    const showNotif = new Notice.notifications.Notification()
      .setNotificationId('notificationId')
      .setTitle(data.title || 'Thông báo')
      .setBody(data.content || 'Bạn có một thông báo mới')
      .setData(data)
      .android.setChannelId('test-channel')
      .android.setSmallIcon('ic_launcher')
      Notice.notifications().displayNotification(showNotif)
  })
}
Thanh Cao
  • 151
  • 5