React-native-firebase: Notification service not working on android when its on the foreground

Created on 19 Aug 2018  路  4Comments  路  Source: invertase/react-native-firebase

I've just implemented firebase cloud messaging from the guide. However, its only working when app is on the background otherwise push notification not registering.

App.js

`import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import firebase from 'react-native-firebase';

export default class App extends React.Component {

componentDidMount() {
    firebase.messaging().hasPermission()
        .then(enabled => {
            if (enabled) {
                firebase.messaging().getToken().then(token => {
                    console.warn('LOG: ', token);
                });
                // user has permissions
            } else {
                firebase.messaging().requestPermission()
                    .then(() => {
                        console.warn('User Now Has Permission');
                    })
                    .catch(error => {
                        console.warn('Error', error);
                        // User has rejected permissions
                    });
            }
        });

    this.messageListener = firebase.messaging().onMessage((message) => {
        console.warn(message, 'TEST');
    });
}

componentWillUnmount() {
    this.messageListener();
}

render() {
    return (
        <View style={styles.container}>
            <Text style={styles.welcome}>
                Welcome to React Native!
            </Text>
            <Text style={styles.instructions}>
                To get started, edit App.js
            </Text>
        </View>
    );
}

}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});`

{ "name": "test", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-react-native-stage-0": "^1.0.1", "eslint-config-rallycoding": "^3.2.0", "jest": "^23.5.0", "jest-react-native": "^18.0.0", "react-test-renderer": "16.3.1" }, "scripts": { "start": "react-native start", "android": "react-native run-android", "ios": "react-native run-ios", "test": "jest" }, "jest": { "preset": "react-native" }, "dependencies": { "react": "16.3.1", "react-native": "~0.55.2", "react-native-firebase": "^4.3.8", "react-native-vector-icons": "^5.0.0", "react-navigation": "^2.11.2" } }
` package="com.test">

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

<application
  android:name=".MainApplication"
  android:label="@string/app_name"
  android:icon="@mipmap/ic_launcher"
  android:allowBackup="false"
  android:theme="@style/AppTheme">
  <activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:launchMode="singleTop"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    android:windowSoftInputMode="adjustResize">
    <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.google.android.geo.API_KEY"
            android:value="AIzaSyBCTUYZED0OnI0wfmxp3WegHTECgIOa26U"/>

    <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>

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

</application>


package com.test;

import com.facebook.react.ReactActivity;
import android.content.Intent;
public class MainActivity extends ReactActivity {

/**
 * Returns the name of the main component registered from JavaScript.
 * This is used to schedule rendering of the component.
 */
@Override
protected String getMainComponentName() {
    return "test";
}

@Override
 public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
 }

}
`

`package com.test;

import android.app.Application;

import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line

import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
       new MainReactPackage(),
                new RNFirebasePackage(),
                new RNFirebaseMessagingPackage() // <-- Add this line
  );
}

@Override
protected String getJSMainModuleName() {
  return "index";
}

};

@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}

@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage / false);
}
}
dependencies {
compile project(':react-native-firebase')
implementation project(':react-native-firebase')
implementation fileTree(dir: "libs", include: ["
.jar"])
implementation "com.android.support:appcompat-v7:27.1.1"
implementation "com.facebook.react:react-native:+" // From node_modules

 implementation "com.google.android.gms:play-services-base:15.0.1"
 implementation "com.google.firebase:firebase-messaging:17.1.0"

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply plugin: 'com.google.gms.google-services'
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
mavenLocal()
google() // <-- Check this line exists and is above jcenter
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
}
}
`

Environment

  1. Application Target Platform:

Running on Android real device.

  1. Development Operating System:

Windows 10

  1. Build Tools:

Webstorm

  1. React Native version:

"react-native": "~0.55.2",

  1. React Native Firebase Version:

    "react-native-firebase": "^4.3.8",

  2. Firebase Module:

messaging

  1. Are you using typescript?

no

Is there a problem about the implementation? I completed the guide from here: https://rnfirebase.io/docs/v4.3.x/messaging/receiving-messages

Most helpful comment

@o7k7 why you have closed this issue I am still getting same issue can you please explain how you have fixed that issue ?

All 4 comments

i was also facing the same problem then one of my junior comes with this solution and i got what was wrong.
https://rnfirebase.io/docs/v4.2.x/messaging/android#Update-Android-Manifest
try this link add tags in android manifest

@o7k7 why you have closed this issue I am still getting same issue can you please explain how you have fixed that issue ?

Same issue here with android >=8.0.0

I was also facing the same issue but after adding lines of code in manifest mentioned in this link https://rnfirebase.io/docs/v4.2.x/messaging/android#Update-Android-Manifest, I was able to listen to notification inside my App.js

Follow the android setup steps mentioned in the link

inside App.js

    // subscribe listner inside componentDidMount
componentDidMount() {
    const channel = new firebase.notifications.Android.Channel(
        'Your channel ID',
        'Channel Name',
        firebase.notifications.Android.Importance.Max
    ).setDescription('A natural description of the channel');
    firebase.notifications().android.createChannel(channel);


    // the listener returns a function you can use to unsubscribe
    this.notificationListener = firebase.notifications().onNotification((notification) => {

        if (Platform.OS === 'android') {

            const localNotification = new firebase.notifications.Notification({
                sound: 'default',
                show_in_foreground: true,
            })
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .android.setChannelId('Your channel ID') // e.g. the id you chose above
                .android.setSmallIcon('ic_notification_icon_white') // create this icon in Android Studio
                .android.setColor('#000000') // you can set a color here
                .android.setPriority(firebase.notifications.Android.Priority.High);

            firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

        } else if (Platform.OS === 'ios') {

            const localNotification = new firebase.notifications.Notification()
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .ios.setBadge(notification.ios.badge);

            firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

        }
    });
}

//Remove listeners allocated in createNotificationListeners()
componentWillUnmount() {
    this.notificationListener();
}
Was this page helpful?
0 / 5 - 0 ratings