Updated 5 March 2021
In this blog, we will learn about how to integrate and receive firebase notification in React Native Android App.
Having Notifications in your mobile applications is one of the basic features these days.
Firebase provides many cool functions that make application development, testing and analytics super easy.
But personally, I feel that there is no competition for firebase in terms of Push Notifications and it will soon be the only way to send notifications to your mobile application users.
Well, there can be many separate blogs for each of the firebase related functionality.
Currently, we will focus on firebase push notification only.
Integrating this super easy, but procedural, please follow through the lines written along.
So, without wasting further time, letโs get started.
1 |
npm install --save react-native-firebase |
Above command will install and save the react-native-firebase package in your React Native Project.
1 |
react-native link react-native-firebase |
This Command will link the react-native-firebase package in your React Native Project.
Now go to your firebase console and set up your android package and app registration over there.
Download the google-services.json file and keep it safe with you.
Now, you need to do some manual changes in your android directory/folder of your React Native Project.
Paste the google-services.json file that you just saved above at path android –> app
Your directory will look something like this :
In your project level build.gradle file (path to this file: android –> build.gradle )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "27.0.3" minSdkVersion = 16 compileSdkVersion = 27 targetSdkVersion = 27 supportLibVersion = "27.1.1" googlePlayServicesVersion = "15.0.0" // Make Sure This line is added over here only } repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.4' classpath 'com.google.gms:google-services:3.2.1' // Make Sure This line is added over here only // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() google() jcenter() maven { url "$rootDir/../node_modules/react-native/android" } maven { url 'https://maven.google.com/' // Make Sure This block is added over here only name 'Google' } } } |
In your module level build.gradle file (path to this file: android–> app–>build.gradle)
1 2 3 4 5 6 7 8 9 |
// other lines of file dependencies { // Your other dependencies implementation project(':react-native-firebase') implementation "com.google.android.gms:play-services-base:15.0.0" implementation "com.google.firebase:firebase-core:15.0.2" implementation "com.google.firebase:firebase-messaging:15.0.2" } |
Now you need to make some changes in your AndroidManifest.xml file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.react.native.myproject"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.VIBRATE" /> <application> <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" /> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_notification_icon" /> </application> </manifest> |
NOTE : -> You need to add default notification_icon in your android drawable folders only so that the default notification icon is replaced by the icon you want to use.
After following the above steps you now need to add and remove some simple listeners to your React native App.js File.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import firebase from 'react-native-firebase'; import type, { Notification, NotificationOpen } from 'react-native-firebase'; componentDidMount() { firebase.messaging().hasPermission().then(hasPermission => { if (hasPermission) { //App already has permission to recieve notifications we just need to add recivers for the notifications this.subscribeToNotificationListeners() } else { //App does not have permission to recieve notifications we first need to request for permission and then add recivers for the notifications firebase.messaging().requestPermission().then(() => { this.subscribeToNotificationListeners() }).catch(error => { console.error(error); }) } }) } // A funtion to subscribe to the notification recievers subscribeToNotificationListeners() { const channel = new firebase.notifications.Android.Channel( 'notification_channel_name', // To be Replaced as per use 'Notifications', // To be Replaced as per use firebase.notifications.Android.Importance.Max ).setDescription('A Channel To manage the notifications related to Application'); firebase.notifications().android.createChannel(channel); this.notificationListener = firebase.notifications().onNotification((notification) => { console.log('onNotification notification-->', notification); console.log('onNotification notification.data -->', notification.data); console.log('onNotification notification.notification -->', notification.notification); // Process your notification as required }); } componentWillUnmount() { this.notificationListener(); } |
After adding these listeners, we now need to handle the Notification received, so we will just modify our listeners a bit like below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
subscribeToNotificationListeners() { const channel = new firebase.notifications.Android.Channel( 'notification_channel_name', // To be Replaced as per use 'Notifications', // To be Replaced as per use firebase.notifications.Android.Importance.Max ).setDescription('A Channel To manage the notifications related to Application'); firebase.notifications().android.createChannel(channel); this.notificationListener = firebase.notifications().onNotification((notification) => { console.log('onNotification notification-->', notification); console.log('onNotification notification.data -->', notification.data); console.log('onNotification notification.notification -->', notification.notification); // Process your notification as required this.displayNotification(notification) }); } displayNotification = (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('notification_channel_name') // e.g. the id you chose above .android.setSmallIcon('ic_notification_icon') // create this icon in Android Studio .android.setColor(colors.colorAccent) // you can set a color here .android.setPriority(firebase.notifications.Android.Priority.High); firebase.notifications() .displayNotification(localNotification) .catch(err => console.error(err)); } } |
And It is done, you will now be able to receive notifications in your React Native Android Application.
Below is a snippet of App.js file with all the changes –>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, BackHandler, ToastAndroid, StatusBar } from 'react-native'; import firebase from 'react-native-firebase'; import type, { Notification, NotificationOpen } from 'react-native-firebase'; // Your Other import lines as per your use case export default class App extends Component { subscribeToNotificationListeners() { const channel = new firebase.notifications.Android.Channel( 'notification_channel_name', // To be Replaced as per use 'Notifications', // To be Replaced as per use firebase.notifications.Android.Importance.Max ).setDescription('A Channel To manage the notifications related to Application'); firebase.notifications().android.createChannel(channel); this.notificationListener = firebase.notifications().onNotification((notification) => { console.log('onNotification notification-->', notification); console.log('onNotification notification.data -->', notification.data); console.log('onNotification notification.notification -->', notification.notification); // Process your notification as required this.displayNotification(notification) }); } displayNotification = (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('notification_channel_name') // e.g. the id you chose above .android.setSmallIcon('ic_notification_icon') // create this icon in Android Studio .android.setColor(colors.colorAccent) // you can set a color here .android.setPriority(firebase.notifications.Android.Priority.High); firebase.notifications() .displayNotification(localNotification) .catch(err => console.error(err)); } } componentDidMount() { firebase.messaging().hasPermission().then(hasPermission => { if (hasPermission) { this.subscribeToNotificationListeners() } else { firebase.messaging().requestPermission().then(() => { this.subscribeToNotificationListeners() }).catch(error => { console.error(error); }) } }) } componentWillUnmount() { this.notificationListener(); } /* Change return block below as per Your Application Logic */ render() { return ( <View> </View> ); } } |
Hope This helps you.
Keep coding and Keep Sharingย
References : –>
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
15 comments
I have a confusion regarding the channel id. I have this setup for channel id
#AndroidManifest.xml
I have used the same string in place of “notification_channel_name” in the above example
// the following code wasn’t allowed in last comment
Inside meta-data tag
android:name=”com.google.firebase.messaging.default_notification_channel_id”
android:value=”pushNotificationChannelId”
I tried to send custom data, and when I come to recover them I can not.
I created a php api.
$ msg = array (‘body’ => ‘Firebase’ , ‘title =>’ Vishal ‘ , ‘ data ‘=> [‘ id ‘=> 12]);
console.log (‘onNotification notification.data ->’, notification.data);
and I get weird info.
please help me
Can you please share some more details ?
A log of what exactly do you receive and what exactly was sent in the PHP Api request would be appreciated.
whats about IOS notification.
Well, the iOS notification also works in a similar fashion.
The react-native code is the same.
Only you need to make changes in the iOS Xcode project and install some additional packages (using cocoa pods) and add the GoogleServicesInfo.Plist file from the firebase into your iOS Project.
You can find the documentation from the official site over here –>
1) https://rnfirebase.io/docs/v5.x.x/installation/ios
2) https://rnfirebase.io/docs/v5.x.x/notifications/ios
This should help you to get along.
Regards,
Anchit