React-native-push-notification: Foreground remote notification not showing in android notification tray

Created on 30 Sep 2020  路  10Comments  路  Source: zo0r/react-native-push-notification

I want to display a notification in the notification tray when a remote notification is received when app is in foreground.

Using FCM on React Native (version "0.61.5") and a android usb-debugging device connected to Android Studios. I receive remote notification sent from Firebase Console when app is in background but when app is in foreground notification doesn't show. It is received and console logged through onNotification in my index.js file.

When I try the example a foregrounded recieved remote notification only trigger an Alert - which I don't want since then the user experience is different depending on if the app is backgrounded or foregrounded.

I've been reading through your documentation and code-example and can't get it to work, what am I missing? :open_mouth:
I've looked at some older (2019) guides but they're all referring to deprecated changes to AndroidManifest using GCM (for more info https://developers.google.com/cloud-messaging/android/android-migrate-fcm ).

I've also got @react-native-firebase/app and @react-native-firebase/messaging installed but since they don't handle foregrounded notifications as far as I've understood I started using this library. :smile:

Important parts from my AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

  <application
    android:name=".MainApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">


        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>

        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

      <meta-data
        android:name="com.dieam.reactnativepushnotification.notification_foreground"
        android:value="false"/>

    <meta-data
      android:name="com.google.firebase.messaging.default_notification_icon"
      android:resource="@drawable/notification_icon"
    />
<activity.... 

From android/build.gradle

buildscript {
    ext {
        googlePlayServicesVersion = "+"
        firebaseMessagingVersion = "+"
        buildToolsVersion = "28.0.3"
        minSdkVersion = 19
        compileSdkVersion = 29
        targetSdkVersion = 29
    }
    repositories {
        google()
        mavenLocal()
        jcenter()
        ...
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:+'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenLocal()...

inside index.js

import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';

PushNotification.configure({
  // (optional) Called when Token is generated (iOS and Android)
  onRegister: token => {
    console.log('TOKEN:', token);
  },

  // (required) Called when a remote is received or opened, or local notification is opened
  onNotification: notification => {
    console.log('NOTIFICATION:', notification);
    // process the notification
    PushNotification.localNotification(notification);
    // (required) Called when a remote is received or opened, or local notification is opened
    notification.finish(PushNotificationIOS.FetchResult.NoData);
  },

  onRegistrationError: err => {
    console.error(err.message, err);
  },

  permissions: {
    alert: true,
    badge: true,
    sound: true
  },
  popInitialNotification: false,
  requestPermissions: true
});

Most helpful comment

SOLVED: I wasn't sending in the specified channelId when I sent my remote notifications from the Firebase Console (I was targeting my plugged in android (using usb-debugging through Android Studios) and only sending notifications to it using it's FCM token and thus not setting a channelId.

For anyone having issues in the future, I used the wonderful example and the class NotifService to create a default channel - I did also try to create my own channel in android/MainAcitvity.Java using code found here https://developer.android.com/training/notify-user/channels#CreateChannel - both ways work and create the channel - which you can check using the following code (also from the example's NotifsService:

PushNotification.getChannels(function(channels) {
      console.log('getchannels gives us', channels);
    });

@Dallas62 you're the best - thank you for helping me and answering quickly - have a great day!

All 10 comments

hi @piavW
Did you search on issue history ? #1671
Regards

Hi @Dallas62 Yes sorry I did a more thorough search just after posting and I added creation of channel (following your example and creating the NotifService and NotificationHandler), I still get NotificationHandler notification: {"channelId": null though which I'm understanding is the issue since as you say, Firebase doesn't provide information about the channel being used.
I've added this
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" tools:replace="android:value" android:value="default-channel-id" />
to AndroidManifest.xml, is that the correct way to tell what channel it should use?

Just f.y.i. for anyone reading this in the future I did a not best-practice but quick-solve of using the localNotif method (as seen in your example) to send a local notification when I received the remote notification in onNotification (for foregrounded app).

Is it normal that you set com.dieam.reactnativepushnotification.notification_foreground to false ?
This might explain your problem

I changed it to "true" but still doesn't show remote notification in notification tray when foregrounded. The remote notification still has "null" as channelId so maybe I'm not setting my channelId correctly?

What's your library version ?

SOLVED: I wasn't sending in the specified channelId when I sent my remote notifications from the Firebase Console (I was targeting my plugged in android (using usb-debugging through Android Studios) and only sending notifications to it using it's FCM token and thus not setting a channelId.

For anyone having issues in the future, I used the wonderful example and the class NotifService to create a default channel - I did also try to create my own channel in android/MainAcitvity.Java using code found here https://developer.android.com/training/notify-user/channels#CreateChannel - both ways work and create the channel - which you can check using the following code (also from the example's NotifsService:

PushNotification.getChannels(function(channels) {
      console.log('getchannels gives us', channels);
    });

@Dallas62 you're the best - thank you for helping me and answering quickly - have a great day!

Hey @Dallas62 can I ask, I'm trying to refactor your NotificationHandler class component to a functional one (to make a API-call with a hook in onNotification), how could I convert the PushNotification.configure({onRegister.... }) code (from your example)?

You can take a look to #1462

You're the best! :)

This is how you can create the channel id
PushNotification.createChannel( { channelId: 'fcm_fallback_notification_channel', // (required) channelName: 'My channel', // (required) channelDescription: 'A channel to categorise your notifications', // (optional) default: undefined. playSound: true, // (optional) default: true soundName: 'default', // (optional) SeesoundNameparameter oflocalNotificationfunction importance: 4, // (optional) default: 4. Int value of the Android notification importance vibrate: true, // (optional) default: true. Creates the default vibration patten if true. }, created => console.log(createChannel returned '${created}'), // (optional) callback returns whether the channel was created, false means it already existed. );

And Now register

`PushNotification.localNotification({
  channelId: 'fcm_fallback_notification_channel',
  title: 'My Notification Title', // (optional)
  message: 'My Notification Message', // (required)
  playSound: true, // (optional) default: true
  soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
  //number: 10, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
  //repeatType: 'day',
});`

For Remote notification just make sure you are using the channelId  that you are getting in notification

`onNotification: function(notification) {
console.log('NOTIFICATION:', notification);
console.log('LOCAL NOTIFICATION ==>', notification);
// process the notification
// notification.finish(PushNotificationIOS.FetchResult.NoData);

},`

Was this page helpful?
0 / 5 - 0 ratings