React native Push notification Locally
Push notification is the feature notify user for any new update or send any message to user like whats app. There are two type of notifications.
1. Local push notification
2. Remote push notification
In this article we discuss about local notification. For remote notification needs (FCM) Firebase cloud messaging service. But many times we need to send notification locally. so this method is try to solve this problem. Follow these steps:
1. Install library for local notification
2. Get Firebase senderId from project settings
3. Set up code for send notification
1. Install library for local notification
First you need to install library in your react native project with this command:
1 |
npm i react-native-push-notification |
2. Get Firebase senderId from project settings
After library installation we need senderId. this id you can generate from Firebase project setting. please follow these steps for get this senderid:
- Login into firebase console with help of this link https://console.firebase.google.com/.
- Now go to project setting under link check below image
- Now click on cloud messaging there you can find this senderId
3. Setup code for local push notification
Before write the code for push notification you need add some lines in android/app/src/main/AndroidManifest.xml
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 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yourapp"> <uses-permission android:name="android.permission.INTERNET"/> <!-- OPTIONAL PERMISSIONS, REMOVE WHATEVER YOU DO NOT NEED --> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> <uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <queries> <!-- Support checking for http(s) links via the Linking API --> <intent> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="https" /> </intent> </queries> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:theme="@style/AppTheme" android:usesCleartextTraffic="true"> <meta-data android:name="com.supersami.foregroundservice.notification_channel_name" android:value="Sticky Title" /> <meta-data android:name="com.supersami.foregroundservice.notification_channel_description" android:value="Sticky Description." /> <service android:name="com.supersami.foregroundservice.ForegroundService"></service> <service android:name="com.supersami.foregroundservice.ForegroundServiceTask"></service> <!-- 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> </application> </manifest> |
Add this link in android/build.gradle
1 2 3 4 5 6 7 8 |
buildscript { ... dependencies { ... classpath('com.google.gms:google-services:4.3.3') ... } } |
In android/app/build.gradle
1 2 3 4 5 6 7 |
dependencies { ... implementation 'com.google.firebase:firebase-analytics:17.3.0' ... } apply plugin: 'com.google.gms.google-services' |
Now you can create a component name with PushController.js and use this component in your parent component. This code trigger local notification automatically.
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 |
import React, {Component} from "react"; import PushNotification, {Importance} from "react-native-push-notification"; import AsyncStorage from '@react-native-async-storage/async-storage'; export default class PushController extends Component{ componentDidMount(){ 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("NOTIFICATION:", notification); // process the notification here // required on iOS only //notification.finish(PushNotificationIOS.FetchResult.NoData); }, // Android only senderID: "XXXXXXXXXXX", //This sender id you can get from firebase account // iOS only permissions: { alert: true, badge: true, sound: true }, popInitialNotification: true, requestPermissions: Platform.OS === 'ios' }); PushNotification.createChannel( { channelId: "mychannel", // (required) channelName: "My channel", // (required) channelDescription: "A channel to categorise your notifications", // (optional) default: undefined. playSound: true, // (optional) default: true soundName: "default", // (optional) See `soundName` parameter of `localNotification` function importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance vibrate: true, // (optional) default: true. Creates the default vibration pattern if true. }, async (created) => { console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed. //await AsyncStorage.setItem("setNotify", 'yes'); this.triggerNotify() } ); } triggerNotify = async () => { PushNotification.localNotification({ //... You can use all the options from localNotifications channelId: "mychannel", title: "MyApp - Your order accepted. ", message: "Click here for check details", // (required) //foreground: false, //date: Date.now() + (10 * 1000), //new Date(todate2), // in 60 secs Date.now() + (10 * 1000) allowWhileIdle: true, // (optional) set notification to work while on doze, default: false //repeatType: 'day', /* Android Only Properties */ repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info. }); } render(){ return null; } } |
This code trigger notification instantly. but you can set its time when you need to trigger local notification with localNotificationSchedule function:
1 2 3 4 5 6 7 8 9 |
PushNotification.localNotificationSchedule({ //... You can use all the options from localNotifications message: "My Notification Message", // (required) date: new Date(Date.now() + 60 * 1000), // in 60 secs allowWhileIdle: false, // (optional) set notification to work while on doze, default: false /* Android Only Properties */ repeatTime: 1, // (optional) Increment of configured repeatType. Check 'Repeating Notifications' section for more info. }); |