Ad

React Native - Can't Access Firebase Push Notification In Foreground In Android

I'm trying to implement push notifications in React Native with Firebase console app by following this article:

React Native: Integrating Push Notifications using FCM

In Android, I'm able to receive notifications when the app is in background but unable to receive in foreground. Using this method to receive notifications:

async createNotificationListeners() {
  /*
   * Triggered when a particular notification has been received in foreground
   * */
  this.notificationListener = firebase
    .notifications()
    .onNotification(notification => {
      console.log("fg", notification);
      const { title, body } = notification;
      this.showAlert(title, body);
    });

  /*
   * If app is in background, listen for when a notification is clicked / tapped / opened as follows:
   * */
  this.notificationOpenedListener = firebase
    .notifications()
    .onNotificationOpened(notificationOpen => {
      console.log("bg", notificationOpen);
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    });

  /*
   * If app is closed, check if it was opened by a notification being clicked / tapped / opened as follows:
   * */
  const notificationOpen = await firebase
    .notifications()
    .getInitialNotification();
  if (notificationOpen) {
    console.log("bg", notificationOpen);
    const { title, body } = notificationOpen.notification;
    this.showAlert(title, body);
  }
  /*
   * Triggered for data only payload in foreground
   * */
  this.messageListener = firebase.messaging().onMessage(message => {
    //process data message
    console.log("fg", JSON.stringify(message));
  });
}

Here, firebase.notifications().onNotification or firebase.messaging().onMessage() are not being triggered at all.

In other solutions, it's because from Android 8 you need to create a channel but I can't find any option to create channel while sending notification from FCM notification composer.

Ad

Answer

Abdul,

You need to make the notification channel using firebase on the device.

const channel = new firebase.notifications.Android
  .Channel('default', 'Default Channel', firebase.notifications.Android.Importance.Max)
  .setDescription('The default notification channel.')

firebase.notifications().android.createChannel(channel)

This will create the channel, you can call it as many times as you want safely (according to the docs). Your onNotification listener looks fine, you just need to set the android channel on the notification that comes in.

  notification.android.setChannelId('default')
Ad
source: stackoverflow.com
Ad