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.