Hello folks. I hope you all are doing well.
In this tutorial, you’re going to learn how to implement push notifications as an app feature using React Native and Firebase.
There are two main ways you can send push notifications to your app users: local and remote. Local notifications are sent from a React Native application, while remote push notifications are sent from the server or a push notification service such as Firebase Cloud Messaging Service (FCM). We will explore both approaches.
What Are Push Notifications?
Push notification is a small message that users receive on a device. They differ from regular pop-ups because they will appear on the device whether or not the user is currently using the site or app that the notification is tied to.
Push notifications work for both browsers and apps. For browsers, push notifications can show up no matter what site a user is on, as long as they’ve opted in to push notifications. They work very similarly for apps, however, they can pop up on a mobile device at any time, regardless of whether the user is on the app.
Prerequisites
This tutorial requires basic knowledge of React Native Development. To set up your development machine, follow the official guide here.
We are going to use react-native-firebase to implement push notifications in React-native.
First create a project in your Google Firebase Console https://console.firebase.google.com/
Adding Firebase to your app
Register your app in Firebase and follow the configuration steps for Android.
Download your google-services.json. Don't forget to place them in the correct folder.
![folder.png](https://gist.github.com/RajanTank/0b0a37343bc323ad065af1bf0d93f1f8/raw/238087785b9316f3651a0ae5d304e7dbf26874c8/folder.png)
Also create your React Native project and enter it's directory
$ react-native init RNPushNotification
$ cd RNPushNotification
Add and link the React Native Firebase package to your app
$ npm install react-native-firebase
$ react-native link react-native-firebase
Configuration Android project
In MainApplication.java
.... | |
.... | |
// Add this two line | |
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; | |
import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; | |
public class MainApplication extends Application implements ReactApplication { | |
private final ReactNativeHost mReactNativeHost = | |
new ReactNativeHost(this) { | |
@Override | |
protected List<ReactPackage> getPackages() { | |
@SuppressWarnings("UnnecessaryLocalVariable") | |
List<ReactPackage> packages = new PackageList(this).getPackages(); | |
// Packages that cannot be autolinked yet can be added manually here, for example: | |
// packages.add(new MyReactNativePackage()); | |
packages.add(new RNFirebaseMessagingPackage()); // add this line | |
packages.add(new RNFirebaseNotificationsPackage()); // add this line | |
return packages; | |
} | |
}; | |
} |
In build.gradle
dependencies { | |
implementation fileTree(dir: "libs", include: ["*.jar"]) | |
//noinspection GradleDynamicVersion | |
implementation "com.facebook.react:react-native:+" // From node_modules | |
//add this line | |
implementation "com.google.firebase:firebase-messaging:20.1.5" | |
implementation "com.google.android.gms:play-services-base:17.2.1" | |
implementation "com.google.firebase:firebase-core:16.0.8" | |
compile(project(':react-native-firebase')) { | |
transitive = false | |
} | |
} | |
// add this line to end of the page | |
apply plugin: 'com.google.gms.google-services' |
In AndroidManifest.xml
<manifest …> | |
<!-- Add this lines --> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> | |
<uses-permission android:name="android.permission.VIBRATE" /> | |
<application ...> | |
<!-- If we want to schedule local notifications, we must also add the following --> | |
<receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/> | |
<receiver | |
android:enabled="true" | |
android:exported="true" | |
android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver"> | |
<intent-filter> | |
<action android:name="android.intent.action.BOOT_COMPLETED"/> | |
<action android:name="android.intent.action.QUICKBOOT_POWERON"/> | |
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/> | |
<category android:name="android.intent.category.DEFAULT" /> | |
</intent-filter> | |
</receiver> | |
<receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true"> | |
<intent-filter> | |
<action android:name="io.invertase.firebase.notifications.BackgroundAction"/> | |
</intent-filter> | |
</receiver> | |
<service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/> | |
<!-- Add this line for Message service --> | |
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService"> | |
<intent-filter> | |
<action android:name="com.google.firebase.MESSAGING_EVENT" /> | |
</intent-filter> | |
</service> | |
<!-- Add this line to enable backgound messaging services --> | |
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService"/> | |
</application> | |
</manifest> |
After everything is set up and configured now, we have to implement the FCM push notification in React Native side using React Native Firebase module.
Receive Push Notifications
Now let's code the most awaited part… Receiving Notifications! 😉
Before integrating the code please install the following dependencies:
npm install @react-native-community/async-storage
Before the app can get any notifications, it is crucial to ask permission from users. If the user didn’t allow your app to receive notifications, it can never get any unless the user explicitly changes it from Settings.
So, let's have write below code in App.js
file
import React, { Component } from "react"; | |
import { Alert, View } from "react-native"; | |
import AsyncStorage from '@react-native-community/async-storage'; | |
import firebase from "react-native-firebase"; | |
class App extends Component { | |
async componentDidMount() { | |
//we check if user has granted permission to receive push notifications. | |
this.checkPermission(); | |
// Register all listener for notification | |
this.createNotificationListeners(); | |
} | |
async checkPermission() { | |
const enabled = await firebase.messaging().hasPermission(); | |
// If Premission granted proceed towards token fetch | |
if (enabled) { | |
this.getToken(); | |
} else { | |
// If permission hasn’t been granted to our app, request user in requestPermission method. | |
this.requestPermission(); | |
} | |
} | |
async getToken() { | |
let fcmToken = await AsyncStorage.getItem('fcmToken'); | |
if (!fcmToken) { | |
fcmToken = await firebase.messaging().getToken(); | |
if (fcmToken) { | |
// user has a device token | |
await AsyncStorage.setItem('fcmToken', fcmToken); | |
} | |
} | |
} | |
async requestPermission() { | |
try { | |
await firebase.messaging().requestPermission(); | |
// User has authorised | |
this.getToken(); | |
} catch (error) { | |
// User has rejected permissions | |
console.log('permission rejected'); | |
} | |
} | |
async createNotificationListeners() { | |
// This listener triggered when notification has been received in foreground | |
this.notificationListener = firebase.notifications().onNotification((notification) => { | |
const { title, body } = notification; | |
this.displayNotification(title, body); | |
}); | |
// This listener triggered when app is in backgound and we click, tapped and opened notifiaction | |
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => { | |
const { title, body } = notificationOpen.notification; | |
this.displayNotification(title, body); | |
}); | |
// This listener triggered when app is closed and we click,tapped and opened notification | |
const notificationOpen = await firebase.notifications().getInitialNotification(); | |
if (notificationOpen) { | |
const { title, body } = notificationOpen.notification; | |
this.displayNotification(title, body); | |
} | |
} | |
displayNotification(title, body) { | |
// we display notification in alert box with title and body | |
Alert.alert( | |
title, body, | |
[ | |
{ text: 'Ok', onPress: () => console.log('ok pressed') }, | |
], | |
{ cancelable: false }, | |
); | |
} | |
render() { | |
return ( | |
<View style={{ flex: 1 }}> | |
<Text>React Native Push Notification</Text> | |
</View> | |
); | |
} | |
} | |
export default App; |
Listening Notifications
We are now ready to listen to push notification events. Before proceeding, you should know about different types of notifications supported by Firebase.
Notification-only messages: These are display messages that are automatically handled by Firebase SDK. Notifications are thrown to the device tray.
Notification + optional data messages: These are also handled by Firebase SDK. Only difference here is when the user taps on notification, your app receives a payload associated with that notification.
Data only messages: These types of notifications are handled exclusively by app. No notification is thrown on the device tray unless the app explicitly does so.
Read Also: How React Native Improves Developer Productivity
After having configured everything correctly we can test directly from the firebase console:
- Go to the Cloud Messaging option in the left pane.
- Click on Send your first message
- Enter your test text, select the Android application to which you want to send the application and click Send.
![firebase.png](https://gist.github.com/RajanTank/fc44cbcf7216400e66d71b8c6e1b1075/raw/4ed042cf6acfd90e16249149b7e6a8a6b06e7260/firebase.png)
![message.png](https://gist.github.com/RajanTank/ad43ec56afa992b986cfd22c242490d5/raw/9201b7169ba8d9fe7de0f224dec130b210a11460/message.png)
here's our notification arrived
![notification.png](https://gist.github.com/RajanTank/037f1b9e65e374b0379b6667a28625c7/raw/a20ccb48facaa171c66e70e0ee27def2e7f7468c/notification.png)
There are few points you should know
When an app is in the background and killed in android and you want to listen to data notification, therefore, you need to implement Headless JS functionality.
Android, When app is Not in background or killed and you tab on Notification react-native-firebase library won't be able to catch title and body of notification. It will show undefined therefore you also need to send title and body in data of notification.
Top comments (5)
A huge RED FLAG here please.
using
npm install react-native-firebase
installs v5.6.0 which is way way deprecated and react native firebase is at v10+Please update this article. It was outdated the moment it was posted.
Hello
You missed this part.
In android/build.grade file,
dependencies {
classpath("com.android.tools.build:gradle:3.4.1")
classpath 'com.google.gms:google-services:4.2.0'
}
repositories {
google()
maven {
url 'maven.google.com'
}
jcenter()
}
everybody can fine this solution on this url
djamware.com/post/5d7773f05d8cdc05...
Thanks
dear sir I got error. I followed all you step by step, as you did above.
Please help me. thanks
what is the type of your error ?