Adding Push Notifications to Your React Native Android Project with Firebase

Muhammet Aydın
4 min readAug 31, 2023

--

Introduction: In today’s mobile app landscape, push notifications play a crucial role in engaging users and keeping them informed about important updates. In this article, we’ll walk through the steps to add push notifications to your React Native Android project using Firebase.

Step 1: Set Up Firebase Project:

https://rnfirebase.io/

  1. Log in to the Firebase Console.
  2. Create a new project or use an existing one.
  3. In the project settings, add an Android app to your project and follow the setup instructions to obtain the google-services.json configuration file.
# Using npm
npm install --save @react-native-firebase/app

Generating Android credentials

On the Firebase console, add a new Android application and enter your projects details. The “Android package name” must match your local projects package name which can be found inside of the manifest tag within the /android/app/src/main/AndroidManifest.xml file within your project.

run cd android && ./gradlew signingReport and store the SHA1 code for adding firebase to app.

Download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.

Configure Firebase with Android credentials

First, add the google-services plugin as a dependency inside of your /android/build.gradle file:

buildscript {
dependencies {
// ... other dependencies
classpath 'com.google.gms:google-services:4.3.15'
// Add me --- /\
}
}

Lastly, execute the plugin by adding the following to your /android/app/build.gradle file:

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // <- Add this line

Autolinking & rebuilding

Once the above steps have been completed, the React Native Firebase library must be linked to your project and your application needs to be rebuilt.

Users on React Native 0.60+ automatically have access to “autolinking”, requiring no further manual installation steps. To automatically link the package, rebuild your project:

# Android apps
npx react-native run-android

Step 2: Setup Firebase Messaging For Notifications

  1. Open a terminal window and navigate to your React Native project directory.
  2. Install the required packages by running:
yarn add @react-native-firebase/messaging

Usage-Requesting permissions

This module provides a requestPermission method which triggers a native permission dialog requesting the user's permission:

import messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}

On Android API level 32 and below, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully.

import {PermissionsAndroid} from 'react-native';
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);

The device state and message contents can also determine whether a Notification will be displayed

Step 3: Handle Push Notifications:

Foreground state messages

import React, { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
function App() {
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
}); return unsubscribe;
}, []);
}

For example, the React Native Alert API could be used to display a new Alert each time a message is delivered.Getting a Device Token

  1. Create a new JavaScript file named getFCMTToken.js (or any preferred name) in your project.
  2. Implement the logic to handle push notifications using Firebase Messaging:
import messaging from '@react-native-firebase/messaging';
let token: string;
const requestUserPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  if (enabled) {
token = (await messaging().getToken()).toString();
} else {
console.log('REQUEST PERMISSION DENIED');
}
};
const getNewFCMToken = async () => {
try {
await requestUserPermission();
console.log('Token:', token);

} catch (error) {
console.error('Error getting new FCM token:', error);
}
};
export default getNewFCMToken;

Step 4: Integrate Push Notifications in Your App:

  1. Import and call the check function in your app’s entry point (e.g., App.js):
function App(): JSX.Element {
androidPermission(); // for android api +33
useEffect(() => {
getNewFCMToken();
const unsubscribe = messaging().onMessage(async remoteMessage => {
// Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
showToast(remoteMessage);// or you can give a alert like above
});
return unsubscribe;
}, []);
  return (
// ... Your app's rendering logic ... );
}
export default App;

Happy coding!

Remember that the technology landscape evolves, so it’s a good idea to consult the official documentation for any updates or changes that might have occurred since the time of writing this article.

--

--

No responses yet