Push Notification in React native

Posted By :Akleem Ahmad |5th July 2023

Push Notification in React Native

 

Push notifications are messages or alerts sent from a server or backend system to a user's device. They let users to receive timely and relevant information even when the app is not actively running or in the foreground. Users can receive push notifications even when they are not currently using or have closed the app.

First, we need to set up a push notification service.

 

Choose a push notification service provider, like Firebase Cloud Messaging (FCM) or OneSignal. 

 

Push Notification Service: Choose a push notification service provider such as Firebase Cloud Messaging (FCM) or OneSignal. 

 

Step1:- Create account in Firebase

Step2:- Register your android/iOS app 

Step3:- Download and then add config file // save the google-services.json  android/app

Step4:- Add firebase Sdk 

Step5:- Synch your project by using Android studio

Step6:- Install Libraries for handling the notification

Step7:- Generate the token 

Step8:- Create a server key by using Firebase cloud messaging 

Step9:- Test push notification by using https://testfcm.com/ URL


 

Way to implements all steps in details

 

1. 1. register an account on Firebase: - If you already have an account in Firebase, you can disregard it; otherwise, you must register an account in Firebase.

2. Create a project in the Firebase dashboard:- it is used to create a space (environment).

3. Need to configure your project with the Firebase project:-

4. Need to register your app with Firebase project

 

… Algorithm for registering your app in Firebase:-

  1. Click on plus icon with the text name is  (Add app) in the Firebase project
  2. Select the Android app 
  3. You need the Android package name to fill out the form (android/app/src/main/java/MY/APP/NEW_ID/MainActivity.java) in Android Studio/vs
  4. You need Debug signing certificate SHA-1  for the full file you form: 

 you need to open your project in Android studio 

Note:- Always open only Android files in the android studio its auto sync  or link your project with android studio

 

  1. How to Generate Debug Signing Certificate SHA-1 5E:8F:16:06:2E:A3:CD:2C:4A:0D:54:78:76:BA:A6:F3:8C:AB:F6: 25

You can run the following command:- 1.  cd android

    ./gradlew signingReport

  1.  After filling the columns you can click on the register button.
  2. Error:- An unexpected error has occurred. [Reason: Oauth client already exists in a different project for package

  name com.notification app and certificate hash 5E:8F:16:06:2E:A3:CD:2C:4A:0D:54:78:76:BA:A6:F3:8C:AB:F6:25  

Basically, the error occurring with miss matches the gradle version.  

 

    8. After registering your app successfully you need some configuration in the gradle file according to the Firebase form.

 

6. After the registering your project successfully you need to install some libraries for Firebase 

  1. npm install --save @react-native-firebase/app
  2. npm install @react-native-firebase/messaging
  3. Use this URL to install libraries:- https://rnfirebase.io/

 

7. We need a device token to interface with Firebase for push notifications.

You can you this url:- https://rnfirebase.io/messaging/notifications

 

8. Need to create a function to generate a device token for notification

 

import message from '@react-native-firebase/messaging'

 useEffect(() => {

   getDeviceToken()

 }, [])

 const getDeviceToken = async () => {

   const token = await message().getToken()

   console.log('token', token) //successfully generated the token 

 }

 

9. You can test it by a fake notification website with generated token URL:-   https://testfcm.com/

 

10. You need filed the  following points:-

  1. Server key, 2.Device Token, 3.Title, 4 body, 5

 

 QUESTION:- How to get Server key

You should go on firebase dashboard and click on project setting and select the cloud messaging we need enable cloud messing, then it will provide the server key 

 

11. After put your server key and device token then you should able to send a notification


 

Basically, there are three types of notifications:

1. Foreground Notification.

BackGround Notification
Notification for Kill mode
 

1. forefront Notification: When an app is in the forefront, it indicates that it is currently visible and being utilised by the user. The user interface is displayed on the screen, and the programme receives priority in terms of system resources. The programme can accept user input, alter its interface in real time, and communicate with the device's hardware and services.
 

2. Background Notification: - When an app is in the background, it is not visible to the user but continues to run in the device's memory. The user may have navigated to a different app or the home screen, yet the app can still conduct some functions in the background. In the background, an app can conduct limited tasks, such as playing audio, getting location updates, and changing data in response to push notifications.

 

3. Kill Mode Notification:- The term 'kill mode' is not widely used in the context of mobile apps. However, it could refer to a condition in which the app's process has been terminated or forced closed by the system or the user. When an app is in this state, it cannot execute code or carry out tasks. It must be relaunched by the user or activated by an external event.

You should write this code in notification handlers. 

useEffect(() => {

   const subscription = messaging().onMessage(async remoteMessage => {

     Alert.alert(JSON.stringify(remoteMessage))

   })

   return subscription

 }, [])

When an app is in the foreground,background and kill mode. This code will auto listen to the notification and generate.

 

Note:- You can use the  https://testfcm.com/ website URL for generate the fake notification



Here is some photos for better understanding 

React Native push notification for Android 


 

Step 1 - Go to Firebase Console and select you project (eg :- Auto-I)

 

Step 2 - Click on plus icon and select Android option

 

 

Step 3 - Follow the instruction to register App

 

Note   1- please find your package name in Android/App/src/main.AndroidManifest.xml

2 - you can generate the SHA-1 key by using following command 

Cd Android.

./gradlew signingReport.

3 - Click on Register button, and after clicking on register button from download and config file, you will obtain google-services.json, download that file, and paste it in Android/App. 



 

Step 4 - On Add Firebase SDK please read and follow the instruction in the below Screenshot 


 

Step 5:- Synch your project by using android studio

Step 6:- Install Libraries for handling the notification

            npm install --save @react-native-firebase/app

            npm install @react-native-firebase/messaging

 

Step 7:- Generate the token 

 code :  app.js file 

useEffect(() => {

        getDeviceToken()

        console.log('token generating')

    }, [])

    const getDeviceToken = async () => {

        console.log('token function')

        let token = await messaging().getToken()

        console.log('token', token) //successfully generated the token 

    }

    useEffect(() => {

        const subscription = messaging().onMessage(async remoteMessage => {

           alert(JSON.stringify(remoteMessage)) //display notification

        })

        return subscription

    }, [])


 

Step8:- Create a server key by using firebase cloud messaging 

 

 

Step9:- Test push notification by using 

       

           https://testfcm.com/ URL

Step 10 - Fill generated server key and generated device token which you will get from console

 



 


About Author

Akleem Ahmad

Akleem is an experienced Backend developer with specialised in Mean technologies. He has practical knowledge and hands-on experience in JavaScript, ReactJs, ReactNative, HTML, CSS, NodeJs and Bootstrap. Akleem has contributed to various client projects, such as Enviuver, Jabburr Social Media app, and many more, showcasing his proficiency in API implementations, map integration, development testing and deployment, as well as his ability to enhance code and deliver high-quality work. He has a creative mindset and good analytical skills, which enable him to think critically and explore new technologies with ease.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us