React Native : Firebase Notification (react-native-firebase Version 7)
In this Blog I show you How to Handle Firebase Push Notification (Use Library react-native-firebase version 7)
Step (1) =>
npx react-native init ProjectName
Step (2) =>
npm install @react-native-community/push-notification-ios
npm install @react-native-firebase/app
npm install @react-native-firebase/messaging
npm install react-native-push-notification
Step (3) =>
Create a project in Firebase console Generate google-services.json put this file in android\app folder
Step (4) =>
In project directory Create src folder and create 2 file FCMService.js another LocalNotificationService.js
import messaging from ‘@react-native-firebase/messaging’
import {Platform} from ‘react-native’;
class FCMService {
register = (onRegister, onNotification, onOpenNotification) => {
this.checkPermission(onRegister)
this.createNotificationListeners(onRegister, onNotification, onOpenNotification)
}
registerAppWithFCM = async() => {
if (Platform.OS === ‘ios’) {
await messaging().registerDeviceForRemoteMessages();
await messaging().setAutoInitEnabled(true)
}
}
checkPermission = (onRegister) => {
messaging().hasPermission()
.then(enabled => {
if (enabled) {
// User has permissions
this.getToken(onRegister)
} else {
// User doesn’t have permission
this.requestPermission(onRegister)
}
}).catch(error => {
console.log(“[FCMService] Permission rejected “, error)
})
}
getToken = (onRegister) => {
messaging().getToken()
.then(fcmToken => {
if (fcmToken) {
onRegister(fcmToken)
}else {
console.log(“[FCMService] User does not have a device token”)
}
}).catch(error => {
console.log(“[FCMService] getToken rejected “, error)
})
}
requestPermission = (onRegister) => {
messaging().requestPermission()
.then(() => {
this.getToken(onRegister)
}).catch(error => {
console.log(“[FCMService] Request Permission rejected “, error)
})
}
deleteToken = () => {
console.log(“[FCMService] deleteToken “)
messaging().deleteToken()
.catch(error => {
console.log(“[FCMService] Delete token error “, error)
})
}
createNotificationListeners = (onRegister, onNotification, onOpenNotification) => {
// When the application is running, but in the background
messaging()
.onNotificationOpenedApp(remoteMessage => {
console.log(‘[FCMService] onNotificationOpenedApp Notification caused app to open from background state:’,remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// When the application is opened from a quit state.
messaging()
.getInitialNotification()
.then(remoteMessage => {
console.log(‘[FCMService] getInitialNotification Notification caused app to open from quit state:’,remoteMessage)
if (remoteMessage) {
const notification = remoteMessage.notification
onOpenNotification(notification)
// this.removeDeliveredNotification(notification.notificationId)
}
});
// Foreground state messages
this.messageListener = messaging().onMessage(async remoteMessage => {
console.log(‘[FCMService] A new FCM message arrived!’, remoteMessage);
if (remoteMessage) {
let notification = null
if (Platform.OS === ‘ios’) {
notification = remoteMessage.data.notification
} else {
notification = remoteMessage.notification
}
onNotification(notification)
}
});
// Triggered when have new token
messaging().onTokenRefresh(fcmToken => {
console.log(“[FCMService] New token refresh: “, fcmToken)
onRegister(fcmToken)
})
}
unRegister = () => {
this.messageListener()
}
}
export const fcmService = new FCMService()
import PushNotification from “react-native-push-notification”;
import PushNotificationIOS from “@react-native-community/push-notification-ios”;
import {Platform} from ‘react-native’;
class LocalNotificationService {
configure = (onOpenNotification) => {
PushNotification.configure({
onRegister: function (token) {
console.log(“[LocalNotificationService] onRegister:”, token);
},
onNotification: function (notification) {
console.log(“[LocalNotificationService] onNotification:”, notification);
if (!notification?.data) {
return
}
notification.userInteraction = true;
onOpenNotification(Platform.OS === ‘ios’ ? notification.data.item : notification.data);
if (Platform.OS === ‘ios’) {
// (required) Called when a remote is received or opened, or local notification is opened
notification.finish(PushNotificationIOS.FetchResult.NoData)
}
},
// IOS ONLY (optional): default: all — Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* — Specified if permissions (ios) and token (android and ios) will requested or not,
* — if not, you must call PushNotificationsHandler.requestPermissions() later
* — if you are not using remote notification or do not have Firebase installed, use this:
* requestPermissions: Platform.OS === ‘ios’
*/
requestPermissions: true,
})
}
unregister = () => {
PushNotification.unregister()
}
showNotification = (id, title, message, data = {}, options = {}) => {
PushNotification.localNotification({
/* Android Only Properties */
…this.buildAndroidNotification(id, title, message, data, options),
/* iOS and Android properties */
…this.buildIOSNotification(id, title, message, data, options),
/* iOS and Android properties */
title: title || “”,
message: message || “”,
playSound: options.playSound || false,
soundName: options.soundName || ‘default’,
userInteraction: false // BOOLEAN: If the notification was opened by the user from the notification area or not
});
}
buildAndroidNotification = (id, title, message, data = {}, options = {}) => {
return {
id: id,
autoCancel: true,
largeIcon: options.largeIcon || “ic_launcher”,
smallIcon: options.smallIcon || “ic_notification”,
bigText: message || ‘’,
subText: title || ‘’,
vibrate: options.vibrate || true,
vibration: options.vibration || 300,
priority: options.priority || “high”,
importance: options.importance || “high”, // (optional) set notification importance, default: high,
data: data,
}
}
buildIOSNotification = (id, title, message, data = {}, options = {}) => {
return {
alertAction: options.alertAction || ‘view’,
category: options.category || “”,
userInfo: {
id: id,
item: data
}
}
}
cancelAllLocalNotifications = () => {
if (Platform.OS === ‘ios’) {
PushNotificationIOS.removeAllDeliveredNotifications();
} else {
PushNotification.cancelAllLocalNotifications();
}
}
removeDeliveredNotificationByID = (notificationId) => {
console.log(“[LocalNotificationService] removeDeliveredNotificationByID: “, notificationId);
PushNotification.cancelLocalNotifications({id: `${notificationId}`})
}
}
export const localNotificationService = new LocalNotificationService()
Step (5)=>
In your App.js file paste this code
import React, {useEffect} from ‘react’
import {View, StyleSheet, Text, Button} from ‘react-native’
import {fcmService} from ‘./src/FCMService’
import {localNotificationService} from ‘./src/LocalNotificationService’
export default function App() {
useEffect(() => {
fcmService.registerAppWithFCM()
fcmService.register(onRegister, onNotification, onOpenNotification)
localNotificationService.configure(onOpenNotification)
function onRegister(token) {
console.log(“[App] onRegister: “, token)
}
function onNotification(notify) {
console.log(“[App] onNotification: “, notify)
const options = {
soundName: ‘default’,
playSound: true //,
// largeIcon: ‘ic_launcher’, // add icon large for Android (Link: app/src/main/mipmap)
// smallIcon: ‘ic_launcher’ // add icon small for Android (Link: app/src/main/mipmap)
}
localNotificationService.showNotification(
0,
notify.title,
notify.body,
notify,
options
)
}
function onOpenNotification(notify) {
console.log(“[App] onOpenNotification: “, notify)
alert(“Open Notification: “ + notify.body)
}
return () => {
console.log(“[App] unRegister”)
fcmService.unRegister()
localNotificationService.unregister()
}
}, [])
return (
<View style={styles.container}>
<Text>Sample React Native Firebase V7</Text>
<Button
title=”Press me”
onPress={() => localNotificationService.cancelAllLocalNotifications()}
/>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: ‘center’,
justifyContent: ‘center’
}
})
Step (6)=>
Simpler in your project index.js file just past this code
import React from ‘react’
import {AppRegistry} from ‘react-native’;
import App from ‘./App’;
import {name as appName} from ‘./app.json’;
import messaging from ‘@react-native-firebase/messaging’;
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log(‘Message handled in the background!’, remoteMessage);
});
function HeadlessCheck({ isHeadless }) {
if (isHeadless) {
// App has been launched in the background by iOS, ignore
return null;
}
return <App />;
}
AppRegistry.registerComponent(appName, () => HeadlessCheck);
Step (8)=>
Finally Run react-native run-android I think it will be helpful for your project Notification part Background and foreground both end