Push Notifications for React Native on Android
Introduction
This guide will teach you how to use Parse to send push notifications to your React Native application on Android. You will set up Firebase and configure your Back4App app to send them via dashboard and Cloud Code functions.
At any time, you can access this project via our GitHub repositories to checkout the complete code.
Prerequisites
To complete this tutorial, you will need:
- A React Native App created and connected to Back4App.
- Understand how to deploy a cloud function on Back4App.
- An active account at Google, so you can use Google Firebase.
Goal
Send push notifications from Parse to a React Native application on Android, using Back4App’s dashboard and Cloud Code functions.
Step 1 - Setting up Firebase
Firebase is the most used service provider for sending and receiving push notifications on Android. It’s used by a wide range of companies nowadays, together with the other various tools. Let’s start by creating a Firebase project for your app following steps 1 and 2 from this documentation.
After creating your app and before exiting Firebase’s console, make sure to download and save the file google-services.json
and also go to the project settings, over the “Cloud Messaging” tab and retrieve the following keys:
- Server key;
- Sender ID.
Step 2 - Enabling Push Notifications on Back4App
To link your Firebase Project with Back4App and enable sending push notifications through your Dashboard and Cloud Code, follow these steps:
-
Go to Back4App Website, log in, find your app and click on
Server Settings
. -
Find the “Android Push notification” block and click on
SETTINGS
>EDIT
. The “Android Push notification” block looks like this:
- Add the Firebase
Server Key
to theAPI Key
field and theSender ID
to theGCM Sender ID
field.
- Save it and you are done.
Step 3 - Installing and Setting Up Dependencies
On your React Native project, let’s install the react-native-push-notification
library, which will integrate the application with Firebase and enable you to handle any received notification. Run the following command on your project root directory:
yarn add react-native-push-notification
After installing it, you still need to add some configurations to the android/app/src/main/AndroidManifest.xml
, android/build.gradle
and android/app/build.gradle
following the library docs.
Make sure to also add in the AndroidManifest.xml
file a meta-data
containing the default notification channel id for your application(let’s use guideChannel
as our example) . You can add the name directly to the directive or include it in the strings.xml
file. Also, place your project’s google-services.json
file at the android/app
directory.
1
2
3
4
5
6
7
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="guideChannel" />
<!-- OR -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id" />
In the next step, we will learn how to use this library and combine it with Parse.
Step 4 - Handling Push Notifications
Let’s create a file with new methods related to push notifications called PushNotificationMethods.js
(or PushNotificationMethods.tsx
) and add the following function, that is responsible for initializing the react-native-push-notification
, creating a notification channel, and also setting up Parse to recognize our device’s push configuration:
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
76
77
78
79
80
81
82
83
84
85
86
87
import PushNotification from 'react-native-push-notification';
import Parse from 'parse/react-native';
const channelId = 'guideChannel';
export async function configurePushNotifications() {
// Initialize PushNotification
await PushNotification.configure({
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
// process the notification
console.log('NOTIFICATION:', notification);
// If notification is remote and has data, trigger local notification to show popup.
// This is needed for Parse sent notifications because Firebase doesn't trigger popup
// notifications with data by itself
if (
notification.data !== undefined &&
notification.data.data !== undefined
) {
try {
// Notification data comes as a stringified JSON, so parsing is needed
const notificationData = JSON.parse(notification.data.data);
// JSON Parse notifications from the dashboard and Cloud Code
// should contain the default `title` and `message` parameters
let title = 'Notification Title';
if (notificationData.title !== undefined) {
title = notificationData.title;
}
let message = 'Noticiation Message';
if (notificationData.message !== undefined) {
message = notificationData.message;
}
// Text Parse notifications from the dashboard only have an `alert` parameter
if (notificationData.alert !== undefined) {
message = notificationData.alert;
}
PushNotification.localNotification({
channelId: channelId,
title: title,
message: message,
});
} catch (error) {
console.log(`Error triggering local notification ${error}`);
}
}
},
onRegister: async function (token) {
console.log(`Registered with device token ${token.token}`);
let deviceToken = token.token;
// Create the notification channel, required for Android notifications
await PushNotification.createChannel({
channelId: channelId,
channelName: 'Guide channel',
});
console.log('Notification channel created!');
// Create a Parse Installation, that will link our application's push notification
// to the Parse server
try {
const installationId = await Parse._getInstallationId();
const Installation = new Parse.Installation();
// Make sure to change any needed value from the following
Installation.set('deviceType', 'android');
Installation.set('GCMSenderId', 'YOUR_GCM_SENDER_ID');
Installation.set('pushType', 'gcm');
Installation.set('appIdentifier', 'YOUR_APP_IDENTIFIER(PACKAGE_NAME)');
Installation.set('parseVersion', '3.2.0');
Installation.set('appName', 'Back4AppGuidePushNotifications');
Installation.set('appVersion', '1.0');
Installation.set('localeIdentifier', 'pt-BR');
Installation.set('badge', 0); // Set initial notification badge number
Installation.set('timeZone', 'America/Sao_Paulo');
Installation.set('installationId', installationId);
Installation.set('channels', [channelId]);
Installation.set('deviceToken', deviceToken);
await Installation.save();
console.log(`Created new Parse Installation ${Installation}`);
} catch (error) {
console.log(error.message);
}
},
popInitialNotification: true,
requestPermissions: true,
});
}
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
76
77
78
79
80
81
82
83
84
85
86
87
import PushNotification from 'react-native-push-notification';
import Parse from 'parse/react-native';
const channelId: string = 'guideChannel';
export async function configurePushNotifications() {
// Initialize PushNotification
await PushNotification.configure({
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification: object) {
// process the notification
console.log('NOTIFICATION:', notification);
// If notification is remote and has data, trigger local notification to show popup.
// This is needed for Parse sent notifications because Firebase doesn't trigger popup
// notifications with data by itself
if (
notification.data !== undefined &&
notification.data.data !== undefined
) {
try {
// Notification data comes as a stringified JSON, so parsing is needed
const notificationData = JSON.parse(notification.data.data);
// JSON Parse notifications from the dashboard and Cloud Code
// should contain the default `title` and `message` parameters
let title: string = 'Notification Title';
if (notificationData.title !== undefined) {
title = notificationData.title;
}
let message: string = 'Noticiation Message';
if (notificationData.message !== undefined) {
message = notificationData.message;
}
// Text Parse notifications from the dashboard only have an `alert` parameter
if (notificationData.alert !== undefined) {
message = notificationData.alert;
}
PushNotification.localNotification({
channelId: channelId,
title: title,
message: message,
});
} catch (error: any) {
console.log(`Error triggering local notification ${error}`);
}
}
},
onRegister: async function (token: {os: string; token: string}) {
console.log(`Registered with device token ${token.token}`);
let deviceToken: string = token.token;
// Create the notification channel, required for Android notifications
await PushNotification.createChannel({
channelId: channelId,
channelName: 'Guide channel',
});
console.log('Notification channel created!');
// Create a Parse Installation, that will link our application's push notification
// to the Parse server
try {
const installationId = await Parse._getInstallationId();
const Installation = new Parse.Installation();
// Make sure to change any needed value from the following
Installation.set('deviceType', 'android');
Installation.set('GCMSenderId', 'YOUR_GCM_SENDER_ID');
Installation.set('pushType', 'gcm');
Installation.set('appIdentifier', 'YOUR_APP_IDENTIFIER(PACKAGE_NAME)');
Installation.set('parseVersion', '3.2.0');
Installation.set('appName', 'Back4AppGuidePushNotifications');
Installation.set('appVersion', '1.0');
Installation.set('localeIdentifier', 'pt-BR');
Installation.set('badge', 0); // Set initial notification badge number
Installation.set('timeZone', 'America/Sao_Paulo');
Installation.set('installationId', installationId);
Installation.set('channels', [channelId]);
Installation.set('deviceToken', deviceToken);
await Installation.save();
console.log(`Created new Parse Installation ${Installation}`);
} catch (error) {
console.log(error.message);
}
},
popInitialNotification: true,
requestPermissions: true,
});
}
Open Source Documentation
More information about theParse.Installation
class can be found here.
Note that the event handler onNotification
method has a code that triggers a local notification in the app after receiving a remote one. Parse requires this code because Firebase doesn’t trigger popup notifications with data by itself. More on that and Android notification types can be read here.
Call this configurePushNotifications
method in your App.js
(or App.tsx
) file after initializing Parse and before declaring your App
content.
App.js
1
2
3
4
5
6
7
8
9
// Other imports
// ...
import {configurePushNotifications} from './src/PushNotificationMethods';
// Your Parse initialization configuration goes here
// ...
// Initialize PushNotifications
configurePushNotifications();
Build and run the application. You can now see an Installation
table in your app’s Back4App dashboard with an entry corresponding to your app.
Step 5 - Sending Push Notifications via Dashboard
We are now ready to send the first push notification to our app. Follow the steps below to send a push message via Back4App’s Dashboard:
-
Go to Back4App Website, log in, find your app and click on
Dashboard
. -
Click on
Push
>Send New Push
and create an audience for your push notification.
- Write your message and look at the preview by clicking on the
Android
option.
- If you have already reviewed the push notification and you want to send it, click on
Send push
.
You may explore the other options for Push Notification at
Parse Dashboard
.
There, it’s also possible to look atPast Pushes
you sent and theAudiences
you created for them.
Step 6 - Sending Push Notifications via Cloud Code
Using Cloud functions starter guide, you can detach reusable methods from your front-end and get complete control of all your backend resources via the master key.
Let’s use cloud code functions to send a push message. First, create a cloud function called sendPush
which calls the Parse.Push.send
method. There are two ways to select which users will receive the notification: querying the Parse.Installation
class or via notification channel names. It’s more common in Android Apps to use channels to distinguish between the users, so let’s use it. Make sure to deploy this function on Back4App before go ahead.
Open Source Documentation
Please check the open source documentation for more details about thesend
method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Parse.Cloud.define('sendPush', async (request) => {
try {
await Parse.Push.send({
channels: [ 'guideChannel' ],
data: {
message: 'Test message',
title: 'Back4App Guide Notification'
}
}, { useMasterKey: true });
return true;
} catch (error) {
return `Error: ${error}`
}
});
Let’s now call the function from the React Native app. Add this function to the PushNotificationMethods.js
(or PushNotificationMethods.tsx
) file and call it in a button inside your application’s main screen:
1
2
3
4
5
6
7
8
export async function sendNotification() {
try {
await Parse.Cloud.run('sendPush');
console.log('Success!');
} catch (error: any) {
console.log(`Error: ${error}`);
}
}
Note that this case of allowing a user to trigger a push notification by himself is not common, we used it here just to show how simple it is to integrate the push notification sending with Parse.
Conclusion
At the end of this guide, you learned how to send Push Notifications using Parse to your React Native application on Android. In the next guide, you will learn how to send them on iOS.