React-native-firebase: onNotification callback is not triggered when app is in foreground (Android).

Created on 22 Sep 2018  路  15Comments  路  Source: invertase/react-native-firebase

I'm working on react-native-firebase push notification, I followed the documentation and set up my project, push notification is coming fine when the app is in the background but one main functionality which I need is to display the notification payload in the foreground as Alert/pop up. But unfortunately, OnNotification is never called when notification is triggered by firebase or postman.

Environment

  1. Application Target Platform:
    android version: 6.0.1

  2. Development Operating System:
    macOS High Sierra

  3. Build Tools:
    VSCode

  4. React Native version:
    react-native-cli: 2.0.1
    react-native: 0.56.1

  5. React Native Firebase Version:
    4.3.8

  6. Firebase Module:
    messaging and notifications

  7. Are you using typescript?
    No

Using postman:-

Header:-
content-type : application/json
authorization: key=AIzaSyDEzlxPIzLkRrxx6vh9EliQ3jydsuBE6fM

Body:-
{
"to":"dw6Zedt31S0:APA91bENem4gs92Shfoeg7rTfCvm9ZygnRXxxYlS2RNRjxZzxj3Ica_wD1aHedc0snsScmTYf8Zu0uv8J67Fy6tPga-19aMJrQ83sj2SmFrog_XLY3uWtiQmVL-gnTOJwcwkb0V2kDV8",
"content_available": true,
"notification": {
"title": "App",
"body": "This would be json response check",
"click_action": "fcm.ACTION.HELLO",
"show_in_foreground": true
},
"data":{
"title": "App",
"body": "This would be json response",
"show_in_foreground": true
}
}

This is my repo you are most welcome to look into it and help me :

https://github.com/Rajkiran93/react-native-firebase-push-notification-demo

Thank you

Stale

Most helpful comment

Any update? I have the Messaging working fine when app is running on background but I can't make it work what app is en foreground

All 15 comments

@awdhootlele that's good but doesn't it is for Messaging rather then notification, And they doesn't mention about this solution(Adding services in manifest) in Notification Doc.

@awdhootlele that's good but doesn't it is for Messaging rather then notification, And they doesn't mention about this solution(Adding services in manifest) in Notification Doc.

They have suggested to follow messaging setup guide for setting up notifications as well. (Below "Android Installation" title)

Any update? I have the Messaging working fine when app is running on background but I can't make it work what app is en foreground

Hello 馃憢, this issue has been automatically marked as stale because it has not had activity for quite some time. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. Thank you for your contributions.

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

Any update here? I have the same problem

actually @awdhootlele solution worked out.

Just add these line into your androidmanifest.xml (It works for me)

<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

Same issue, I am receiving message from fcm and firebase.notifications().onNotificationOpened is working fine while app in background but firebase.notifications().onNotification is not triggered when app in foreground

Androidmanifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.knowledgeupdateapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <!-- < Only if you're using GCM or localNotificationSchedule() > -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission
        android:name="com.knowledgeupdateapp.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.knowledgeupdateapp.permission.C2D_MESSAGE" />
    <!-- < Only if you're using GCM or localNotificationSchedule() > -->

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

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

      <meta-data android:name="com.facebook.sdk.ApplicationId"
          android:value="@string/facebook_app_id"/>

      <meta-data android:name="com.google.android.geo.API_KEY"
        android:value="<Removed APIkey>"/>


      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                android:value="YOUR NOTIFICATION CHANNEL NAME"/>
      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="YOUR NOTIFICATION CHANNEL DESCRIPTION"/>
      <!-- Change the resource name to your App's accent color - or any other color you want -->
      <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@android:color/white"/>


      <receiver
      android:name="com.google.android.gms.gcm.GcmReceiver"
      android:exported="true"
      android:permission="com.google.android.c2dm.permission.SEND" >
      <intent-filter>
          <action android:name="com.google.android.c2dm.intent.RECEIVE" />
          <category android:name="com.knowledgeupdateapp" />
      </intent-filter>
    </receiver>

    <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" />
      </intent-filter>
    </receiver>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm" android:exported="false" >
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      </intent-filter>
    </service>

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

    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
      <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
      </intent-filter>
    </service>

 <!-- Background Messages (Optional) -->

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

    </application>

</manifest>

App.js

import React, {Component} from 'react';
import {
  StyleSheet,
  Dimensions,
  Platform,
  View,
  StatusBar,
  DrawerLayoutAndroid,
} from 'react-native';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import DropdownAlert from 'react-native-dropdownalert';


import reducer from './app/Redux/reducers';
import { setNavigator, setActiveRoute } from "./app/Redux/actions";
import DrawerContent from './app/Navigation/DrawerContent';
import Toolbar from './app/Navigation/Toolbar';
import AppNavigation from './app/Navigation/AppNavigation';
import { bgStatusBar, bgDrawer } from './app/global.styles';
import { ScrollView } from 'react-native-gesture-handler';
import firebase from 'react-native-firebase';

let store = createStore(reducer);
/* getDrawerWidth       Default drawer width is screen width - header width
* https://material.io/guidelines/patterns/navigation-drawer.html
*/
const getDrawerWidth = () => Dimensions.get('window').width - (Platform.OS === 'android' ? 56 : 64);

export default class App extends Component {
  constructor() {
    super();

    this.drawer = React.createRef();
    this.navigator = React.createRef();
  }

  async componentDidMount() {
    store.dispatch(setNavigator(this.navigator.current));

    //this will get initial notification
    // when can we use this: this can be use if app running in background at that time
    // we receive notification, during on tap of notification we will get data
    const notificationOpen = await firebase.notifications().getInitialNotification();
    console.log("--", notificationOpen)
    if (notificationOpen) {
      const action = notificationOpen.action;
      const notification = notificationOpen.notification;
      var seen = [];
      // if you send custom data in additional option you can access those data like below
      alert(JSON.stringify(notification.data, function(key, val) {
          if (val != null && typeof val == "object") {
              if (seen.indexOf(val) >= 0) {
                  return;
              }
              seen.push(val);
          }
          return val;
      }));
    }
    const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
                .setDescription('My apps test channel');

    // Create the channel
    firebase.notifications().android.createChannel(channel);

    this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification) => {
        // 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.
        console.log("invoked display listener")
    });

    this.notificationListener = firebase.notifications().onNotification((notification) => {
      // Process your notification as required
      console.log("invoked onnotification listener")

      notification
          .android.setChannelId('test-channel')
      firebase.notifications()
          .displayNotification(notification);

    });

    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      console.log("invoked notification open")
        // 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 = [];
        alert(JSON.stringify(notification.data, function(key, val) {
            if (val != null && typeof val == "object") {
                if (seen.indexOf(val) >= 0) {
                    return;
                }
                seen.push(val);
            }
            return val;
        }));
        firebase.notifications().removeDeliveredNotification(notification.notificationId);
    });

    this.messageListener = firebase.messaging().onMessage((message) => {
      // Process your message as required
      console.log("message listener")
    });
  } 

  componentWillUnmount() {
      this.notificationDisplayedListener();
      this.notificationOpenedListener();
      this.notificationListener();
  }



  openDrawer = () => {
    this.drawer.current.openDrawer();
  };

  closeDrawer = () => {
    this.drawer.current.closeDrawer();
  }; 

  getActiveRouteName = navigationState => {
    if (!navigationState) {
      return null;
    }
    const route = navigationState.routes[navigationState.index];
    // dive into nested navigators
    if (route.routes) {
      return getActiveRouteName(route);
    }
    return route.routeName;
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <Provider store={store}> 
          <DrawerLayoutAndroid
            drawerWidth={getDrawerWidth()}
            drawerPosition={DrawerLayoutAndroid.positions.Left}
            renderNavigationView={
              () => <DrawerContent closeDrawer={this.closeDrawer} />
            }
            drawerBackgroundColor={bgDrawer}
            ref={this.drawer}
          >
            <View style={styles.container}>
              <StatusBar
                  translucent
                  backgroundColor={bgStatusBar}
                  animated
              />
              <Toolbar showMenu={this.openDrawer} />
              <AppNavigation
                onNavigationStateChange={(prevState, currentState) => {
                  const currentScreen = this.getActiveRouteName(currentState);
                  store.dispatch(setActiveRoute(currentScreen));
                }}
                ref={this.navigator}
              />
            </View>
          </DrawerLayoutAndroid>
        </Provider>
        {/* common notification component */}
        <DropdownAlert ref={ref => global.dropDownAlertRef = ref}  closeInterval={2000} tapToCloseEnabled={true} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  },
});

It would be great if anyone help me to fix this

Hi guys,

My problem is fixed by below changes. I am using react-native-push-noticiation and aslo react-native-firebase I just changed my Androidmanifest.xml. Moved my react-native-firebase service code before react-native-push-notification service like below

 <!-- first react-native-firebase  -->
     <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
      <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
      </intent-filter>
    </service>

 <!-- Background Messages (Optional) -->

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

 <!-- next react-native-push-notification  -->
    <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" />
      </intent-filter>
    </receiver>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm" android:exported="false" >
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      </intent-filter>
    </service>

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

Now my onNotification get trigged and also onNotificationOpen working fine

Hi guys,

My problem is fixed by below changes. I am using react-native-push-noticiation and aslo react-native-firebase I just changed my Androidmanifest.xml. Moved my react-native-firebase service code before react-native-push-notification service like below

 <!-- first react-native-firebase  -->
     <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
      <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
      </intent-filter>
    </service>

 <!-- Background Messages (Optional) -->

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

 <!-- next react-native-push-notification  -->
    <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" />
      </intent-filter>
    </receiver>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm" android:exported="false" >
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      </intent-filter>
    </service>

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

Now my onNotification get trigged and also onNotificationOpen working fine

This works for me as well. Thanks.

Hi guys,

My problem is fixed by below changes. I am using react-native-push-noticiation and aslo react-native-firebase I just changed my Androidmanifest.xml. Moved my react-native-firebase service code before react-native-push-notification service like below

 <!-- first react-native-firebase  -->
     <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
        <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
      <intent-filter>
        <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
      </intent-filter>
    </service>

 <!-- Background Messages (Optional) -->

  <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />

 <!-- next react-native-push-notification  -->
    <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" />
      </intent-filter>
    </receiver>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationRegistrationService"/>

    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerServiceGcm" android:exported="false" >
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      </intent-filter>
    </service>

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

Now my onNotification get trigged and also onNotificationOpen working fine

Thanks. This works for me.

Which version of react-native-push-notification and react-native-firebase was this solution?

Was this page helpful?
0 / 5 - 0 ratings