Firebase FCM

What is Push Notification?
Firebase Push notifications based these 2 things.
  • Server key: It will be provided by firebase cloud messaging API, need to enable in google cloud console.
  • FCM Registration: Device Token, It will be generated by fcm token method in user application
Push notifications are messages or alerts sent by the makers of an application the user has installed.
There are two main types of notifications, namely foreground and background notifications:
  • Foreground: A notification is a notification type that the user gets when the app is currently open and running.
  • Foreground: Background: Background notifications are sent whether or not the app is currently open.
Push notifications are popular in the world for several reasons:
  • Its being used for advertise products and offers.
  • Improve overall user experience.
  • Sending of transaction receipts faster.
  • Product Marketing and Selling.
Push Notification Architecture in React Native:
  • Android: FCM
  • iOS: APNS
React Native Push Notification

Create Project in Firebase

Create App in Firebase, As I have create TodoApp
1-Click on "Create Project +" 2-Enter title for project then continue 3-Click on project setting 4-Download googl-service.json file 4-Move this googl-service.json file inside android folder 5-Go to Project Overview in Firebase
Firebase
Click on General
Firebase
Scroll to bottom for project setting
Firebase

Cloud Messaging in Firebase

Cloud Messaging
Click on Cloud Messaging tab, we will get some details Sender ID Server Key
Firebase

Messaging in Firebase

Messaging in Firebase
Click on message tab in sidebar menu Click on "Create your first campaign"
Firebase

Firebase Messaging onBoadring

Firebase Messaging onBoadring popup will appear
Select "Firebase Notification Messages" option
Firebase
Select "Firebase In-App Messages" option I we select "Firebase In-App Messages" option click on link: Firebase In-App Messages

Firebase Notification Messages

Firebase Notification Messages
Compose Notification
Here we can write push notification messages
Firebase
Scroll to bottom
Firebase

Firebase In-App Messages

Firebase In-App Messages
Click on General
Firebase

Write Function in Project

Install & Setup
  • Register Project in firebase.console
  • @react-native-firebase/app
  • @react-native-firebase/messaging
Subscribing to messages
  • onMessage: handle FCM messages when app is alive/in foreground
  • setBackgroundMessageHandler: handles FCM messages when app is in a killed/inactive state
  • Request for permission in app
                          
                            import AsyncStorage from '@react-native-async-storage/async-storage';
                            import messaging from '@react-native-firebase/messaging';
    
                            export async function requestUserPermission() {
                              const authStatus = await messaging().requestPermission();
                              const isApproved =
                                authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
                                authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    
                              if (isApproved) {
                                // console.log('Authorization status: ', authStatus);
                                getFCMToken();
                              } else {
                                console.log('Authorization status failed');
                                showError('Authorization status:  Failed');
                              }
                            }
                          
                        
  • Generate device token for user in app
                          
                            import AsyncStorage from '@react-native-async-storage/async-storage';
                            import messaging from '@react-native-firebase/messaging';
                            import {showError} from '../util/helper';
                            import {Linking} from 'react-native';
                            import {base_url} from './../util/linking';
                            const getFCMToken = async () => {
                                let fcmToken = await AsyncStorage.getItem('fcmToken');
                                console.log('Old saved FCM Token------->', fcmToken);
                                if (!fcmToken) {
                                  try {
                                    const new_fcmToken = await messaging().getToken();
                                    if (new_fcmToken) {
                                      console.log('New  generated FCM Token====>', new_fcmToken);
                                      await AsyncStorage.setItem('fcmToken', new_fcmToken);
                                    }
                                  } catch (error) {
                                    // console.log('FCM Token not generated*********', error);
                                    showError(error.message);
                                  }
                                }
                            };
                          
                        
  • Create NotificationListener
                          
                            export const notificationListener = () => {
                              messaging().onNotificationOpenedApp(msg => {
                                console.log('onOpened in background state', msg);
                                Linking.openURL(base_url + msg.data.screen);
                              });
    
                              messaging().onMessage(async msg => {
                                console.log('Received in forground on Message===========>', msg);
                              });
    
                              messaging()
                                .getInitialNotification()
                                .then(msg => {
                                  if (msg) {
                                    console.log('Initial inactive state', msg.notification);
                                  }
                                });
                            };
                          
                        
  • Create unsubscribe method for fcm notification
                          
                          export const unsubscribeFCMNotification = () => {
                            const unsubscribe = messaging().onMessage(async remoteMessage => {
                              Alert.alert('A new FCM message arrived !', JSON.stringify(remoteMessage));
                            });
                            return unsubscribe;
                          };
                          
                        
  • Call notification function
                          
                          import React, {useEffect} from 'react';
                          import {Button, StyleSheet, View} from 'react-native';
                          import {notificationListener, requestUserPermission} from '../fcm-services';
    
                          export const ScreenA = () => {
                            useEffect(() => {
                              requestUserPermission();
                              notificationListener();
                              // unsubscribeFCMNotification();
                            }, []);
    
                            return (
                               <View style={styles.container}>
                                 <RemoteNotification />
                                 <Button title={'Click Here'} onPress={() => console.log('Button clicked')} />
                               </View>
                            );
                          };
                          const styles = StyleSheet.create({
                            container: {
                              flex: 1,
                              alignItems: 'center',
                              justifyContent: 'center',
                              backgroundColor: 'white',
                            },
                          });
                          
                        

Remote & Local Notification

Remote Notification
                
                  import {useEffect} from 'react';
                  import {PermissionsAndroid, Platform} from 'react-native';
                  import PushNotification from 'react-native-push-notification';

                  const checkApplicationPermission = async () => {
                    if (Platform.OS === 'android') {
                      try {
                        await PermissionsAndroid.request(
                          PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
                        );
                      } catch (error) {
                        console.error(error);
                      }
                    }
                  };

                  const RemoteNotification = () => {
                    useEffect(() => {
                      checkApplicationPermission();
                      PushNotification.getChannels(function (channel_ids) {
                        channel_ids.forEach(id => {
                          PushNotification.deleteChannel(id);
                        });
                      });
                      PushNotification.configure({
                        onRegister: function (token) {
                          console.log('Token Generated=====>', token);
                        },

                        onNotification: function (notification) {
                          const {message, title, name, id} = notification;
                          let strTitle: string = JSON.stringify(title).split('"').join('');
                          let strBody: string = JSON.stringify(message).split('"').join('');
                          let strName: string = JSON.stringify(name).split('"').join('');
                          const key: string = JSON.stringify(id).split('"').join('');
                          PushNotification.createChannel(
                            {
                              channelId: key,
                              channelName: 'Remote Message',
                              channelDescription: 'Notification for remote',
                              importance: 4,
                              vibrate: true,
                            },
                            created => console.log(`Remoted Channel cretaed=======> ${created}`),
                          );
                          PushNotification.localNotification({
                            channelId: key,
                            title: strTitle,
                            message: strBody,
                            name: strName,
                          });
                          console.log(
                            'REMOTE NOTIFICATION===>',
                            title,
                            message,
                            name,
                            id,
                            notification,
                          );
                        },
                        senderID: 'xxxxxxxxxx',
                        popInitialNotification: true,
                        requestPermissions: true,
                      });
                    }, []);
                    return null;
                  };

                  export default RemoteNotification;
                
              
Local Notification
                
                import PushNotification from 'react-native-push-notification';
                const LocalNotification = () => {
                  const key = Date.now().toString();
                  PushNotification.createChannel(
                    {
                      channelId: key,
                      channelName: 'Local message',
                      channelDescription: 'Notification for local message',
                      importance: 4,
                      vibrate: true,
                    },
                    created => console.log(`createdChannel returned ${created}`),
                  );
                  PushNotification.localNotification({
                    channelId: key,
                    title: 'Local Message',
                    message: 'Saten Push Message',
                  });
                };

                export default LocalNotification;
                
              
Use created notification component
                
                  import React, {useEffect} from 'react';
                  import {Button, StyleSheet, View} from 'react-native';
                  import {notificationListener, requestUserPermission} from '../fcm-services';

                  export const ScreenA = () => {
                    useEffect(() => {
                      requestUserPermission();
                      notificationListener();
                      // unsubscribeFCMNotification();
                    }, []);

                    return (
                        <View style={styles.container}>
                          <RemoteNotification />
                          <Button title={'Click Here'} onPress={() => console.log('Button clicked')} />
                        </View>
                    );
                  };
                  const styles = StyleSheet.create({
                    container: {
                      flex: 1,
                      alignItems: 'center',
                      justifyContent: 'center',
                      backgroundColor: 'white',
                    },
                  });