Implementing React Native Push Notifications in Android Apps
May 19th, 2021 | By Aman Mittal | 8 min read
Creating and sending React Native Push Notifications in Android apps is a strategic way to boost user engagement with a mobile application.
According to some analysis, push notifications increase app engagement by 88%. It’s also curious that the click-through rate for push notifications on Android (4.06%) is much higher than on iOS (1.7%).
See how to implement push notifications as an app feature using React Native and Firebase. We will be testing out the notification feature on an Android device, but you can go ahead and try it out on iOS yourself.
There are two main ways to send push notifications to your app users: locally and remotely.
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 (FCM).
We explore both approaches.
Requirements
Please make sure you have the following installed on your local development environment and have access to the services mentioned below:
Nodejs (>=10.x.x) with npm and yarn installed
React-native-cli
Windows and Linux users must be running an Android emulator or a physical device via USB
Active Firebase project
To learn more about how to set up a development environment for React Native using react-native-cli, please refer to the official documentation.
You can find the complete code for this tutorial in this GitHub repository.
Install and Set Up react-native-push-notifications
The react-native-push-notifications library helps you set up controllers to consume local or remote notifications for iOS and Android devices.
Follow the instructions in the terminal window. Create a new React Native project and then install this library.
react-native init RNnotifications
cd RNnotifications
yarn add react-native-push-notification
iOS devices: this library depends on the manual installation instructions mentioned at PushNotificationIOS, an API maintained by react-native-community.
Android devices: make the following edits in the appropriate files mentioned below. These modifications allow us to link native capabilities. First, open the file android/build.gradle and add the following:
buildscript {
ext {
googlePlayServicesVersion = "<Your play services version>" // default: "+"
firebaseMessagingVersion = "<Your Firebase version>" // default: "+"
// Other settings
compileSdkVersion = <Your compile SDK version> // default: 23
buildToolsVersion = "<Your build tools version>" // default: "23.0.1"
targetSdkVersion = <Your target SDK version> // default: 23
supportLibVersion = "<Your support lib version>" // default: 23.1.1
}
repositories {
google()
jcenter()
}
dependencies {
// add the following dependency for remote notifications to work
classpath ('com.google.gms:google-services:4.3.3')
}
}
Next, open android/app/build.gradle and add the following:
dependencies {
...
implementation 'com.google.firebase:firebase-analytics:17.3.0'
...
}
apply plugin: 'com.google.gms.google-services'
In the above step, add native bindings to allow the Firebase backend to send and receive notifications remotely.
If you are not looking forward to using remote notifications, you can ignore the above step. However, the following steps apply to both types:
Open the android/app/src/main/AndroidManifest.xml file. Before the <application> tag, add the following:
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application ....>
<!-- Change the value to true to enable pop-up for in foreground on receiving remote notifications (for prevent duplicating while showing local notifications set this to false) -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_foreground"
android:value="false"/>
<!-- Change the resource name to your App's accent color - or any other color you want -->
<meta-data android:name="com.dieam.reactnativepushnotification.notification_color"
android:resource="@color/white"/> <!-- or @android:color/{name} to use a standard color -->
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationActions" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
<receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
<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"/>
</intent-filter>
</receiver>
<service
android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Lastly, go to android/app/src/res/values/colors.xml. If the file does not exist, create it. This file determines the color of the notification on an Android device.
For example, the notification can be white.
<resources>
<color name="white">#FFF</color>
</resources>
Note: To use this library with Expo, you have to eject the Expo SDK app.
Configure Local Push Notifications
Write a configure function to trigger a local notification when a button is pressed.
Create a new file, src/services/LocalPushController.js.
Start by importing PushNotification from the library you initialized in the previous step.
import PushNotification from 'react-native-push-notification'
Add PushNotification.configure() to the file. This accepts an object with the required method onNotification.
This method handles what happens after the notification is opened or received, and it has to be invoked, whether local or remote.
The demo application only invokes a console statement stating the properties of the local notification object used in the current demo app.
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log('LOCAL NOTIFICATION ==>', notification)
},
popInitialNotification: true,
requestPermissions: true
})
Next, export LocalNotification in the snippet below, which gets invoked when a button is pressed by the user or as the value of the onPress attribute.
export const LocalNotification = () => {
PushNotification.localNotification({
autoCancel: true,
bigText:
'This is local notification demo in React Native app. Only shown, when expanded.',
subText: 'Local Notification Demo',
title: 'Local Notification Title',
message: 'Expand me to see more',
vibrate: true,
vibration: 300,
playSound: true,
soundName: 'default',
actions: '["Yes", "No"]'
})
}
PushNotification.LocalNotification has many properties for each mobile platform (iOS or Android).
From the above snippet, properties like vibrate, vibration, bigText, and subText are Android only. However, properties like actions, titles, messages, playSound, and soundName are cross-platform.
Import this method into the App.js file. Import LocalNotification from the src/services/LocalPushController.js file.
Inside the functional App component, add a handler method handleButtonPress to invoke only when the user presses the button.
import React from 'react'
import { Text, View, Button, StyleSheet } from 'react-native'
import { LocalNotification } from './src/services/LocalPushController'
const App = () => {
const handleButtonPress = () => {
LocalNotification()
}
return (
<View style={styles.container}>
<Text>Press a button to trigger the notification</Text>
<View style={{ marginTop: 20 }}>
<Button title={'Local Push Notification'} onPress={handleButtonPress} />
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
buttonContainer: {
marginTop: 20
}
})
export default App
Now, from a terminal window, run react-native and run-android. Make sure you have a device connected via USB and have USB debugging enabled, or you can test on an Android Emulator.
The output of the above code snippet should look like this:
When the button is pressed, it displays the notification, vibrates the device, and plays a default notification sound.
Expanding the notification displays the message from bigText. Pressing the notification results in triggering the console statement from the onNotification method.
You can add scheduled notifications by using PushNotification.localNotificationSchedule(details: Object) method, or you can repeat after a particular time too.
The official documents have more instructions on how to do this or add more customizations.
Configure Remote Notifications
Integrate the Cloud Messaging Service using Firebase to test how remote notifications work. Make sure you have an active Firebase project.
From the main Dashboard page, go to Project Settings. In the Your Apps section, click on Add App and set up a new Android app.
Next, it will ask you to register the application.
Download the file google-services.json and save it at the location android/app/ inside your React Native project.
Then, open the Android/app/build.gradle file and add the following:
dependencies {
implementation project(':react-native-push-notification')
// ... rest remains same
}
// at the end of the file, add
apply plugin: 'com.google.gms.google-services'
Next, create a new service file called RemotePushController.js inside the src/services/ directory. This file contains all the configurations needed to handle a remote push notification.
Inside the mandatory onNotification method, let us again display the result of the remote notification in the console.
It also requires a mandatory Android property called senderID. This can be fetched from Project Settings > Cloud Messaging.
import React, { useEffect } from 'react'
import PushNotification from 'react-native-push-notification'
const RemotePushController = () => {
useEffect(() => {
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log('TOKEN:', token)
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log('REMOTE NOTIFICATION ==>', notification)
// process the notification here
},
// Android only: GCM or FCM Sender ID
senderID: '256218572662',
popInitialNotification: true,
requestPermissions: true
})
}, [])
return null
}
export default RemotePushController
Also, the Cloud Messaging service works using a Token between the App and the notification service. The onRegister method registers the remote server and obtains this token.
You can view this by adding a console statement.
The controller component returns null to avoid effects on the final layout. Add this method inside the App.js file as shown below:
// after other import statements
import RemotePushController from './src/services/RemotePushController'
// before the ending <View>
<RemotePushController />
</View>
Go to the Cloud Messaging section and compose a notification to test.
Click the button Send a test message. You will have the following output:
The Log in the terminal is shown for the same notification.
You can customize the title, message, and other behavior of the Firebase Cloud Messaging service to send notifications at a particular time or date.
Conclusion
Congratulations! You have successfully implemented both ways to send a push notification in a React Native app.
Go ahead and try to implement a scheduled notification as a challenge.
If you are developing commercial React Native apps with sensitive logic, protect them against code theft, tampering, and reverse engineering by following our guide.
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
Create a React Native Image Recognition App with Google Vision API
In this tutorial, you'll learn how to use the Google Vision API to identify the content of images in a React Native mobile application.
February 13, 2019 | By Aman Mittal | 8 min read
From React to React Native in 30 Minutes
Learn how to make a iOS app, using React Native, in 30 minutes
September 2, 2015 | By José Magalhães | 5 min read