SlideShare a Scribd company logo
1 of 15
Implementation of
Push Notification in
React Native Android
app using Firebase
=
What are Push Notifications?
Push notifications are messages that
are sent to a user's device from an
app or website, even when the user
is not actively using the app or
website.
Push notifications can help increase
user engagement and retention by
providing timely and relevant
information to users.
Setting up React Native App
Create a react native app by running:
npx react-native init projectName
Go to
android/app/src/main/java/com/projectName/MainAct
ivity.java
Copy the package name from there.(usually like
com.projectName)
Install necessary firebase packages by running:
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
Prerequisite: React Native - Setting up the development
environment
Setting up React Native App
Go to `/android/build.gradle` and add the lines like
below:
buildscript {
dependencies {
// ... other dependencies
classpath 'com.google.gms:google-
services:4.3.15'
// Add this line --- /
}
}
Then go to `/android/app/build.gradle` folder and add
the lines like below:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' //
<- Add this line
Run the application: First start metro using the command:
npx react-native start
Then run on simulator using: npx react-native run-android
Setting Up Firebase
To use push notifications with React Native, you need to set
up Firebase and configure your app to use Firebase Cloud
Messaging (FCM).
Go to firebase console and create a new project.
Add an android app inside this project by clicking on the
android icon in the add app section.
Paste the package name that you copied earlier.
Give a nickname for the app and for now let's skip the SHA1
key.
Click next and then download the configuration file
generated. Put this file inside ‘android/app’ folder.
Creating a Notification Channel
In Android, you need to create a notification channel to
handle push notifications. This allows users to customize the
behavior of notifications from your app.
To do that head over to
`android/app/src/main/java/com/projectName/MainAc
tivity.java`
And add the below lines along with other imports:
import android.os.Bundle;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
Photo by Denny Müller
Creating a Notification Channel
Then inside the class MainActivity add the below code:
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("500",
"MainChannel",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setShowBadge(true);
notificationChannel.setDescription("Important notifications");
notificationChannel.enableVibration(true);
notificationChannel.enableLights(true);
notificationChannel.setVibrationPattern(new long[] { 400, 200, 400 });
// notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(notificationChannel);
}
super.onCreate(savedInstanceState);
}
Here we are creating a channel named MainChannel with channel id 500
and customising the options for this channel. We are making the channel
priority to high so that we can get headsup notification banner when
receiving the notification.
Registering for push notifications
We need to ask for the permission to display notification for that we
need to use the following code:
import {PermissionsAndroid} from 'react-native';
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS
.POST_NOTIFICATIONS);
When the application is in a background or quit state, you need to
setup a background callback handler via the
setBackgroundMessageHandler method.
To setup a background handler, call the
setBackgroundMessageHandler outside of your application logic as
early as possible:
So we will be adding the handler in the index.js file:
import messaging from '@react-native-firebase/messaging';
messaging().setBackgroundMessageHandler(async
remoteMessage => {
console.log('Message handled in the background!',
remoteMessage);
});
Registering for push notifications
To send messages to a device, you would need the FCM token for it,
which you can get using the messaging().getToken() method.
await messaging().registerDeviceForRemoteMessages();
const token = await messaging().getToken();
// save the token to the db
We will pass this token to the backend server so that notification can
be sent to our device using the token.
Sending test notifications to the
device
To send test notifications to a device, you would need the FCM token
and the server key.
To get the FCM token use the below code and console the output to
get the token in you console(since we are not implementing the server
side here. To test the notification we need to have the token)
await messaging().registerDeviceForRemoteMessages();
const token = await messaging().getToken();
console.log(‘Token: ‘,token);
To get the server key, go to firebase console and go to the project
settings page. Navigate to Cloud Messaging tab. The Cloud
Messaging API (Legacy) will be disabled by default. Enable it and then
you will be provided with a server key. Copy this server key.
Sending test notifications to the
device
Open up Postman and create a new HTTP request. Give the url as:
https://fcm.googleapis.com/fcm/send
Method: POST
Content-Type: application/json
Authorization: key=<server key that you copied>
Body (raw,JSON):
{
"to" : "<device token you copied>",
"notification" : {
"body" : "Body of Your Notification",
"title": "Title of Your Notification",
"android_channel_id": "500"
}
}
Here we use android_channel_id to specify which channel to use to
deliver the notification for the user.
Handling Push Notifications
In your React Native app, since we are sending the cloud
message as notification the notification will be automatically
displayed when in quit and background state, since we
added a handler for that in our index.js file.
If the application is active and running in the foreground then
the notification won't be shown in the notification bar. But we
can write a handler to handle what to do when a notification
comes when app is in foreground state.
We can either perform a task inside the app upon receiving
the notification or we can use a package like Notifee to
display the notification as a heads up banner.
Customizing Push Notifications
You can customize the appearance of the push notifications.
To change the icon in the notification banner,
Generate notification icon using Android Studio
Then go to
`android/app/src/main/AndroidManifest.xml`
Change the first line to:
`<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">`
And add below line inside application tag
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon
" android:resource="@drawable/ic_small_icon" />
Note: ic_small_icon is the icon name specified while generating the icon set
using android studio.
Customizing Push Notifications
To change color of the notification icon:
Go to `android/app/src/main/res/values/colors.xml`
If not found create the file.
add:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="notification_color">hexcolorcode</color>
</resources>
Replace hexcolorcode with the hex code of the color you want.
The go to : `android/app/src/main/AndroidManifest.xml`
Change the first line to:
`<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">`
Add the below line inside the application tag:
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification_color"
tools:replace="android:resource" />
Conclusion
Push notifications can be a powerful
tool for engaging and retaining users
in your React Native app. By using
Firebase and the Notifee library, you
can easily implement push
notifications in your app.

More Related Content

Similar to Implementation of Push Notification in React Native Android app using Firebase.pptx

Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKAjay Chebbi
 
Android Wearables ii
Android Wearables iiAndroid Wearables ii
Android Wearables iiKetan Raval
 
Google I/O 2016 replay - Android N Development
Google I/O 2016 replay - Android N DevelopmentGoogle I/O 2016 replay - Android N Development
Google I/O 2016 replay - Android N DevelopmentTowhidul Haque Roni
 
Android Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docxAndroid Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docxkarthikaparthasarath
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsDigamber Singh
 
Flash messages in node js using connect flash module
Flash messages in node js using connect flash moduleFlash messages in node js using connect flash module
Flash messages in node js using connect flash moduleKaty Slemon
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidDenis Minja
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialAbid Khan
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersAmbarish Hazarnis
 
Configure &amp; send push notification on i os device
Configure &amp; send push notification on i os deviceConfigure &amp; send push notification on i os device
Configure &amp; send push notification on i os deviceShepHertz
 
anugula2setupbyshubham
anugula2setupbyshubhamanugula2setupbyshubham
anugula2setupbyshubhamShubham Verma
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Lou Sacco
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updatedGhanaGTUG
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialKaty Slemon
 
Urban Airship and Android Integration for Push Notification and In-App Notifi...
Urban Airship and Android Integration for Push Notification and In-App Notifi...Urban Airship and Android Integration for Push Notification and In-App Notifi...
Urban Airship and Android Integration for Push Notification and In-App Notifi...Zeeshan Rahman
 
Urban Airship & Android Application Integration Document
Urban Airship & Android Application Integration DocumentUrban Airship & Android Application Integration Document
Urban Airship & Android Application Integration Documentmobi fly
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgetsPrajyot Mainkar
 

Similar to Implementation of Push Notification in React Native Android app using Firebase.pptx (20)

Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDK
 
Android Wearables ii
Android Wearables iiAndroid Wearables ii
Android Wearables ii
 
Google I/O 2016 replay - Android N Development
Google I/O 2016 replay - Android N DevelopmentGoogle I/O 2016 replay - Android N Development
Google I/O 2016 replay - Android N Development
 
Android Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docxAndroid Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docx
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
Flash messages in node js using connect flash module
Flash messages in node js using connect flash moduleFlash messages in node js using connect flash module
Flash messages in node js using connect flash module
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Ng2 cli
Ng2 cliNg2 cli
Ng2 cli
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - Beginners
 
Configure &amp; send push notification on i os device
Configure &amp; send push notification on i os deviceConfigure &amp; send push notification on i os device
Configure &amp; send push notification on i os device
 
anugula2setupbyshubham
anugula2setupbyshubhamanugula2setupbyshubham
anugula2setupbyshubham
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updated
 
Android app development guide for freshers by ace web academy
Android app development guide for freshers  by ace web academyAndroid app development guide for freshers  by ace web academy
Android app development guide for freshers by ace web academy
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
 
Urban Airship and Android Integration for Push Notification and In-App Notifi...
Urban Airship and Android Integration for Push Notification and In-App Notifi...Urban Airship and Android Integration for Push Notification and In-App Notifi...
Urban Airship and Android Integration for Push Notification and In-App Notifi...
 
Urban Airship & Android Application Integration Document
Urban Airship & Android Application Integration DocumentUrban Airship & Android Application Integration Document
Urban Airship & Android Application Integration Document
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 

Recently uploaded

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Implementation of Push Notification in React Native Android app using Firebase.pptx

  • 1. Implementation of Push Notification in React Native Android app using Firebase =
  • 2. What are Push Notifications? Push notifications are messages that are sent to a user's device from an app or website, even when the user is not actively using the app or website. Push notifications can help increase user engagement and retention by providing timely and relevant information to users.
  • 3. Setting up React Native App Create a react native app by running: npx react-native init projectName Go to android/app/src/main/java/com/projectName/MainAct ivity.java Copy the package name from there.(usually like com.projectName) Install necessary firebase packages by running: yarn add @react-native-firebase/app yarn add @react-native-firebase/messaging Prerequisite: React Native - Setting up the development environment
  • 4. Setting up React Native App Go to `/android/build.gradle` and add the lines like below: buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google- services:4.3.15' // Add this line --- / } } Then go to `/android/app/build.gradle` folder and add the lines like below: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // <- Add this line Run the application: First start metro using the command: npx react-native start Then run on simulator using: npx react-native run-android
  • 5. Setting Up Firebase To use push notifications with React Native, you need to set up Firebase and configure your app to use Firebase Cloud Messaging (FCM). Go to firebase console and create a new project. Add an android app inside this project by clicking on the android icon in the add app section. Paste the package name that you copied earlier. Give a nickname for the app and for now let's skip the SHA1 key. Click next and then download the configuration file generated. Put this file inside ‘android/app’ folder.
  • 6. Creating a Notification Channel In Android, you need to create a notification channel to handle push notifications. This allows users to customize the behavior of notifications from your app. To do that head over to `android/app/src/main/java/com/projectName/MainAc tivity.java` And add the below lines along with other imports: import android.os.Bundle; import android.app.NotificationChannel; import android.app.NotificationManager; import android.os.Build; Photo by Denny Müller
  • 7. Creating a Notification Channel Then inside the class MainActivity add the below code: @Override protected void onCreate(Bundle savedInstanceState) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel("500", "MainChannel", NotificationManager.IMPORTANCE_HIGH); notificationChannel.setShowBadge(true); notificationChannel.setDescription("Important notifications"); notificationChannel.enableVibration(true); notificationChannel.enableLights(true); notificationChannel.setVibrationPattern(new long[] { 400, 200, 400 }); // notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(notificationChannel); } super.onCreate(savedInstanceState); } Here we are creating a channel named MainChannel with channel id 500 and customising the options for this channel. We are making the channel priority to high so that we can get headsup notification banner when receiving the notification.
  • 8. Registering for push notifications We need to ask for the permission to display notification for that we need to use the following code: import {PermissionsAndroid} from 'react-native'; PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS .POST_NOTIFICATIONS); When the application is in a background or quit state, you need to setup a background callback handler via the setBackgroundMessageHandler method. To setup a background handler, call the setBackgroundMessageHandler outside of your application logic as early as possible: So we will be adding the handler in the index.js file: import messaging from '@react-native-firebase/messaging'; messaging().setBackgroundMessageHandler(async remoteMessage => { console.log('Message handled in the background!', remoteMessage); });
  • 9. Registering for push notifications To send messages to a device, you would need the FCM token for it, which you can get using the messaging().getToken() method. await messaging().registerDeviceForRemoteMessages(); const token = await messaging().getToken(); // save the token to the db We will pass this token to the backend server so that notification can be sent to our device using the token.
  • 10. Sending test notifications to the device To send test notifications to a device, you would need the FCM token and the server key. To get the FCM token use the below code and console the output to get the token in you console(since we are not implementing the server side here. To test the notification we need to have the token) await messaging().registerDeviceForRemoteMessages(); const token = await messaging().getToken(); console.log(‘Token: ‘,token); To get the server key, go to firebase console and go to the project settings page. Navigate to Cloud Messaging tab. The Cloud Messaging API (Legacy) will be disabled by default. Enable it and then you will be provided with a server key. Copy this server key.
  • 11. Sending test notifications to the device Open up Postman and create a new HTTP request. Give the url as: https://fcm.googleapis.com/fcm/send Method: POST Content-Type: application/json Authorization: key=<server key that you copied> Body (raw,JSON): { "to" : "<device token you copied>", "notification" : { "body" : "Body of Your Notification", "title": "Title of Your Notification", "android_channel_id": "500" } } Here we use android_channel_id to specify which channel to use to deliver the notification for the user.
  • 12. Handling Push Notifications In your React Native app, since we are sending the cloud message as notification the notification will be automatically displayed when in quit and background state, since we added a handler for that in our index.js file. If the application is active and running in the foreground then the notification won't be shown in the notification bar. But we can write a handler to handle what to do when a notification comes when app is in foreground state. We can either perform a task inside the app upon receiving the notification or we can use a package like Notifee to display the notification as a heads up banner.
  • 13. Customizing Push Notifications You can customize the appearance of the push notifications. To change the icon in the notification banner, Generate notification icon using Android Studio Then go to `android/app/src/main/AndroidManifest.xml` Change the first line to: `<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">` And add below line inside application tag <meta-data android:name="com.google.firebase.messaging.default_notification_icon " android:resource="@drawable/ic_small_icon" /> Note: ic_small_icon is the icon name specified while generating the icon set using android studio.
  • 14. Customizing Push Notifications To change color of the notification icon: Go to `android/app/src/main/res/values/colors.xml` If not found create the file. add: <?xml version="1.0" encoding="utf-8"?> <resources> <color name="notification_color">hexcolorcode</color> </resources> Replace hexcolorcode with the hex code of the color you want. The go to : `android/app/src/main/AndroidManifest.xml` Change the first line to: `<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">` Add the below line inside the application tag: <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/notification_color" tools:replace="android:resource" />
  • 15. Conclusion Push notifications can be a powerful tool for engaging and retaining users in your React Native app. By using Firebase and the Notifee library, you can easily implement push notifications in your app.