React Native Android Push Notification with Firebase Cloud Messaging



It takes a lot of work to create mobile and web applications from scratch. Thankfully, open-source packages have simplified the need for developers to start from scratch when creating applications.

 Additionally, cloud service providers offer platforms that facilitate rapid development and hosting of web, iOS, and Android application applications.

Not only are in-app features crucial, but push notifications are also necessary to get users to return to your app.

One of the greatest tools for developing React Native Android push notifications is Firebase cloud messaging(fcm). 

We'll go over the many reasons Firebase is a valuable tool for Android or ios developers in this tutorial, along with a step-by-step tutorial on how to add push notifications to React Native Firebase Messaging.

Why use Firebase?

Notification and messaging functions improve app user engagement. Choose React Native with Firebase if you're looking to develop a reliable notification system so you are able to integrate push notifications.

Firebase provides an abundance of integrated functions and features that are ready for integration, helping developers to swiftly design application backends.

Developers can simultaneously integrate Firebase Cloud Messaging (FCM), a messaging service, across several platforms. It works with web, Unity, iOS, Android.

Firebase Reactive Native Push Notification can be used for:

  • Notify users or send them data messages.
  • Segment users and address distinct user groups with different messaging.
  • Put toast messages and other messages to be noticed into action.

React Native + Firebase Push Notification

To use React Native FCM to add React Native Firebase push notifications, follow the steps below.

1. Set up Firebase Project

Open the Firebase console and login with credential to get started. 

Click on "Create a Project" to start the process of creating a new project and accept the terms & conditions unless you have set up already.




2. Enable Firebase Cloud Messaging API

After creating your project, navigate to the Project Overview.

You will see the list of your project(s).

Click on the "Settings icon", which is just beside of your project name. 


Now enable the Cloud Messaging API to get the "Server Key", which will be required further to send the React Native Android Push Notifications.




3. Set up React Native App

i. Create a React Native App

$ react-native init firebasepushnotification

The Android application can be started by using the following line of code:

$ react-native run-android

ii. Install react-native-push-notification NPM

When it comes to integrating push notifications into your React Native application, you have many choices. The react-native-firebase package is a popular option that provides comprehensive Firebase features for React Native Android Apps.

$ npm install --save react-native-push-notification


4. Register your App on the Firebase Dashboard

Start by registering your React Native iOS or Android application in the Firebase dashboard. Give your iOS or Android app a suitable name when you register it. Next, download the google-services.json file and make sure it is placed in the application module's root directory.

5. Set up React Native Firebase Cloud Messaging

We must configure our React Native application using Firebase credentials to integrate it with Firebase.

Place the following classpath inside the buildscripts/dependencies tags of your android/build.gradle file:

classpath 'com.google.gms:google-services:4.4.1'


In the /android/app/build.gradle file, below the line apply plugin: "com.android.application", insert the google-services plugin as follows:

apply plugin: 'com.google.gms.google-services'

Include the below code in AndroidManifest.xml


<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="${applicationId}.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application .......>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
android:value="CHANNEL NAME"/>
<meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
android:value="CHANNEL DESCRIPTION"/>
<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="${applicationId}" />
</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.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
... </application>


Configure FCM on your React Native APP

Use the GitHub code snippet to run PushNotification.configure at the start of your application. Import this code into your App.js file after placing it in a separate JavaScript file.

import React, { Component } from "react";
import PushNotification from "react-native-push-notification";

export default class CustomPushController extends Component {
  componentDidMount() {
    PushNotification.configure({
      onTokenGenerated: function (token) {
        console.log("Generated Token is:", token);
      },
      onNotificationReceived: function (notification) {
        console.log("Notification Received :", notification);
        notification.finish(PushNotificationIOS.FetchResult.NoData);
      },
      androidSenderID: "**********",
      iosPermissions: {
        alert: true,
        badge: true,
        sound: true
      },
      popInitialNotification: true,
      requestPermissions: true
    });
  }
 
  render() {
    return null;
  }
}


Use this code on your App.js


import React, { Fragment } from 'react';
import PushController from './PushController';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  FlatList
} from 'react-native';

const pushData = [
  {
    pushTitle: "First push",
    pushMessage: "First push message"
  },
  {
    pushTitle: "Second push",
    pushMessage: "Second push message"
  }
];

const renderItem = ({ item }) => (
  <View key={item.pushTitle}>
    <Text style={styles.title}>{item.pushTitle}</Text>
    <Text style={styles.message}>{item.pushMessage}</Text>
  </View>
);

const App = () => {
  return (
    <Fragment>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.scrollView}
        >
          <View style={styles.listHeader}>
            <Text>Push Notifications</Text>
          </View>
          <View style={styles.body}>
            <FlatList
              data={pushData}
              renderItem={renderItem}
              keyExtractor={(item) => item.pushTitle}
            />
          </View>
        </ScrollView>
      </SafeAreaView>
      <PushController/>
    </Fragment>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: 'lightgray'
  },
  listHeader: {
    backgroundColor: '#eee',
    color: "#222",
    height: 44,
    padding: 12
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    paddingTop: 10
  },
  message: {
    fontSize: 14,
    paddingBottom: 15,
    borderBottomColor: "#ccc",
    borderBottomWidth: 1
  },
  body: {
    backgroundColor: 'white',
    paddingHorizontal: 20,
    paddingVertical: 10
  }
});

export default App;


Now Run your App

Now you can run your react native Firebase push notification application and send push notifications through Firebase cloud messaging.

Happy coding✌

Frequently Asked Questions

What is React Native Firebase messaging?

For iOS and Android, React Native Firebase offers native Firebase Cloud Messaging (FCM) connectivity. FCM is a free service that enables communication between devices as well as between servers and devices.

How to send push notifications from one device to another in React Native?

A push notification token must be collected while registering the app on Firebase to use push notifications in a React Native application. This token is a long string that gives each device a unique identity. Next, we'll send a notice, manage the notifications we've sent and received, and save the token in a database on the server.

How do I use Firebase cloud messaging API?

Using the Firebase cloud messaging API, you can build message requests and send them to targets.
How to push notifications in Android using Firebase Cloud Messaging?
By following the steps I mentioned above you can successfully push notifications in Android using Firebase Cloud Messaging.

How do I add Firebase cloud messaging?

You can add Firebase cloud messaging by registering your app on the Firebase console and enabling the firebase cloud messaging API.


codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post