Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
FCM Push Notification with React Native FCM

How to setup FCM Push Notification with React Native…

  • March 11, 2019March 11, 2019
  • by Coder Kai

If you are new to firebase and FCM this article will be useful to setup FCM Push Notification with React Native application. We will be using react-native-firebase(doc: https://rnfirebase.io/docs/v5.x.x/getting-started) module to retrieve token for the push notifications.

Prerequisites

First, create the Firebase account and download the google-services.json file from the console.

  1. Access your firebase account and go to the project settings from the top gear icon.
  2. Create an app if you don’t have it already.
    Download the google-services.json
  3. Go to the Cloud Messages section and add a server key
  4. Download the google-services.json file from the General Page(refer 2nd point). Copy the google-services.json to the android/app/ folder of your react-native project.

 

Configuring react-native-firebase modules

If you can visit the documentation you will be able to follow the steps. But I’m gonna add here the specific steps that you need to setup it in Android application.

1. Install the library

npm install --save react-native-firebase
// or
yarn add react-native-firebase

2. Add gradle dependency under android/app/build.gradle

dependencies {
  // ...
  implementation "com.google.android.gms:play-services-base:16.0.1"
  implementation "com.google.firebase:firebase-core:16.0.7"
  implementation "com.google.firebase:firebase-messaging:17.4.0"
}

Check for the existing first two lines of the dependencies and choose the correct library for it. You can use following mvn repositories to find the correct version

https://mvnrepository.com/artifact/com.google.firebase/firebase-messaging?repo=google
https://mvnrepository.com/artifact/com.google.android.gms/play-services-base
https://mvnrepository.com/artifact/com.google.firebase/firebase-core

When finding the peer version, try to match it with the release date since most are working properly within a particular period of releases.

3. Add the RNFirebaseMessagingPackage to your android/app/src/main/java/com/[app name]/MainApplication.java

// ...
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // <-- Add this line

public class MainApplication extends Application implements ReactApplication {
    // ...

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

4. Update android manifest file.

<application ...>

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

</application>

//For RNFB versions less than 5.2.0 only; add the instance ID service:

<application ...>

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

</application>

Finally try build the application with above configurations

Troubleshooting

Most of the time you will get an error like following.

The library com.google.android.gms:play-services-basement is being requested by various other libraries at [[15.0.1,15.0.1]], but resolves to 16.1.0.Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

If you get the different version error and check whether you have strict versions in the android/build.gradle

def googlePlayServicesVersion = '15.0.1'

configurations.all {
      resolutionStrategy {
          eachDependency { DependencyResolveDetails details ->
              if (requested.group == 'com.google.android.gms') {
                  details.useVersion "$googlePlayServicesVersion"
              }
              Obsolete under new firebase
              if (requested.group == 'com.google.firebase') {
                  details.useVersion "$googlePlayServicesVersion"
              }
          }
      }
  }

This will set the google.android.gms version to be strict to a defined version.
Comment it out if you want it to use the versions of your modules and use the module version defined of the the android/app/build.gradle file.

Still if you get this error add the following line to the bottom of the android/app/build.gradlefile. But I highly urge you not to do so. But it can be tolerated since there arent any mediator who controls the versions of the modules that we use. Maybe we should have something like that in future.

com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

Implementing FCM Push Notification with React Native.

Go to your codebase and add following.

import firebase, { Notification, RemoteMessage } from 'react-native-firebase';


// add following code to an appropriate place.
// implement notifications as needed

  if (Platform.OS === 'android') {
    try {
      const res = await firebase.messaging().requestPermission();
      const fcmToken = await firebase.messaging().getToken();

      if (fcmToken) {
        logger.log('FCM Token: ', fcmToken);

        const enabled = await firebase.messaging().hasPermission();
        if (enabled) {
          logger.log('FCM messaging has permission:' + enabled)
        } else {
          try {
            await firebase.messaging().requestPermission();
            logger.log('FCM permission granted')
          } catch (error) {
            logger.log('FCM Permission Error', error);
          }
        }
        firebase.notifications().onNotificationDisplayed((notification: 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.
          logger.log('Notification: ', notification)
        });

        this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
          logger.log('Notification: ', notification)
        });

      } else {
        logger.log('FCM Token not available');
      }
    } catch (e) {
      logger.log('Error initializing FCM', e);
    }
  }

Background Notifications

If you need to display background notifications, you will have to add following HeadlessTask on index.js file of your codebase.

import { AppRegistry } from 'react-native';
import App from './App';
import firebase, { RemoteMessage } from 'react-native-firebase';

// Move to a proper place
const handleFCMNotification = async (message: RemoteMessage) => {
  console.log('FCM OFFLINE: ', message);
  return Promise.resolve();
}

AppRegistry.registerComponent('myapp', () => App);// your main app component 
// FCM background message task
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => PushNotificationService.handleFCMNotification);

How to Test

Go to  your Firebase Console and go to the Cloud Messaging under Grow section.

FCM Push Notification with React Native

Then select Send Your First Message.

Add test title and notification text, which is the message body. Click on Send Test Message

Add the token retrieved from the frontend logs when running your app.

Fill the other details and click on Review and Then Publish.

This message should be then appearing on the intended device as a notification.

 

Troubleshooting

You might get following error when requesting the token or any Firebase FCM Push Notification with React Native.

The [[DEFAULT]] firebase app has not been initialized!

Solved the issue by removing  xmlns:tools="http://schemas.android.com/tools"  and tools:node="replace"from AndroidManifest.xml. It should be two lines in separate places.

 

More

If you are into react native, feel free to check this tutorial on configuring AWS AppSync Graphql for  react-native apps

Use AWS GraphQL for React Native Message App

 

Query definition in GraphQL and frequent errors with Apollo Client
How to use AWS Ingress ALB with EKS
Coder Kai
A humble developer
android fcm firebase ios notification push react-native

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
Javascript Booleans and Equality
04. Javascript Guide Booleans and…
How to add Chakra UI Animations
Chakra UI Animations
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
How to fetch data with useEffect
How to fetch data with…
add styles to stripe elements
How to add styles to…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
debounce with react hooks
Avoid multiple clicks using debounce…
react-native heap limit allocation
Android/iOS React-native heap limit allocation…
androidx fileprovider
AndroidX ClassNotFound Exception: “android.support. v4.content…
Numbers inJavascript
02. Javascript Guide – Numbers
  • Pingback: Android/iOS React-native heap limit allocation failed error()

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • "oppna binance-konto on AndroidX ClassNotFound Exception: “android.support. v4.content .FileProvider”
  • binance signup on How to use Typescript with arrays
  • LewisLousA on Add SASS in webpack React Redux project

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress