Implementing a Firebase plugin in react-native

Implementing a Firebase plugin in react-native intro:

Here we are going to discuss about “Implementing a Firebase plugin in react-native”, there is already 2 steps which is step1 and step2 before this tutorial please follow this tutorials, so you can easily set up whole firebase notification.

Output is look like –

https://www.itechinsiders.com/ - react native firebase 1

So let’s start implementing the project.

Step 1 – Import the firebase

Firstly you need to import the plugin

import firebase from 'react-native-firebase';

Step 2- Method call

Call your method within component did mount.

componentDidMount() { 
  this.checkNotification(); 
}

Step 3 – Definition of checkNotification()

Now we are going to provide the definition of the checkNotification() function.

checkNotification(){
 const fcmToken = firebase.messaging().getToken();
 const enabled = firebase.messaging().hasPermission();
 if (fcmToken) {
  if (enabled) {
   this.notificationListener = 
   firebase.notifications().onNotification((notification) => {
    console.log('Notification: ', notification)
    console.log('FCM messaging has permission:', enabled)
    })
  }
  else {
    try {
     firebase.messaging().requestPermission();
     console.log('FCM permission granted')
    } catch (error) {
    console.log('FCM Permission Error', error);
   }
  }
 }
//this method used to display the notification at the time of app in foreground
firebase.notifications().onNotificationDisplayed((notification) => { console.log('Notification:-------------- ', notification) }); 
}

Step 4 – App.js code

Your complete App.js file is look like –

import React, {Component} from 'react';
import {Alert} from 'react-native';
import {Scene, Actions, Stack, Tabs} from 'react-native-router-flux';
import firebase from 'react-native-firebase';
import AsyncStorage from '@react-native-community/async-storage';
import Router from '@router';

export default class App extends Component {
  async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners(); //add this line
  }

  //1
  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    console.log('fcmToken', enabled);
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  //3
  async getToken() {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    console.log('fcmToken', fcmToken);
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        // user has a device token
        await AsyncStorage.setItem('fcmToken', fcmToken);
      }
    }
  }

  //2
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

 async createNotificationListeners() {
    /*
     * Triggered when a particular notification has been received in 
     foreground
     * */
    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        console.log(
          '-------notification-------',
          notification,
          notification._title,
          notification._body,
        );
        const title = notification._title;
        const body = notification._body;
        this.showAlert(
          title,
          body,
          notification._data,
          notification._data.notificationType,
        );
      });

    /*
     * If your app is in background, you can listen for when a 
    notification is clicked / tapped / opened as follows:
     * */
    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened(notificationOpen => {
        console.log(
          '-------notificationOpenedListener-------',
          notificationOpen,
        );
        let event_detail = notificationOpen.notification._data;
        const title = event_detail.title;
        const body = event_detail.body;
        this.showAlert(
          title,
          body,
          event_detail,
          event_detail.notificationType,
        );
      });

    /*
     * If your app is closed, you can check if it was opened by a 
      notification being clicked / tapped / opened as follows:
     * */
    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      const {title, body} = notificationOpen.notification;
      console.log(
        '-------notificationOpen-------',
        notificationOpen,
        title,
        body,
      );
      this.showAlert(title, body, notificationOpen);
    }
    /*
     * Triggered for data only payload in foreground
     * */
    this.messageListener = firebase.messaging().onMessage(message => {
      console.log('-------messageListener-------', message);
      //process data message
      this.showAlert(message);
      console.log(JSON.stringify(message));
    });
  }

  //common function for page redirection
  showAlert(title, body, notification, notification_type) {
      Alert.alert(
        // 'spruce', body,
        title ,
        body,
       
      );
 }

  componentWillUnmount() {
    this.notificationListener();
    this.notificationOpenedListener();
  } 

  render() {
    console.log('Hay App.js');
    return <Router />;
  }
}

Expected issue

Issue 1 –

If you start the notification testing after done all setup but still not received the notification then close the app and send notification again, it may happen because of the app is in the foreground, so test it.

Issue 2 –

If you get the notification but your app.js file code is not triggered then please check your AndroidManifest.XML file for following code if present then fine otherwise add it.

<!--Notification permission-->
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

 <!-- Notification code start-->
    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" />
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
    <receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
      <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"/>
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>
    <!-- Notification code end-->

Complete AndroidManifest.xml (android/app/src/main/AndroidManifest.xml) file look like –

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.kindergartenparent">

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.CAMERA"/>

  <uses-feature android:name="android.hardware.camera" android:required="false" />
  <uses-feature android:name="android.hardware.camera.front" android:required="false" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

  <!--Notification permission-->
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


  <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/AppTheme">



    <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode" android:windowSoftInputMode="adjustResize" android:exported="true">
    </activity>

    <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

    <!-- Notification code start-->
    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher" />
    <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>

    <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
    <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
    <receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
      <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"/>
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>
    <!-- Notification code end-->

  </application>

</manifest>

Test The Notification:

Let’s start to test the firebase notification, these are the steps for sending push notifications.

  • For sending push notification go to your firebase console then go to the Cloud Messaging under Grow section, look like below
https://www.itechinsiders.com/ - react native firebase 2
  • Then select Send Your First Message.
https://www.itechinsiders.com/ - react native firebase 3
  • Now add the test title and notification text, which is the message body after that click on Next
https://www.itechinsiders.com/ - react native firebase 4
  • Then choose your package name and click on Review and Then Publish.

Expected issues: 

  • Problem: You attempted to use a firebase module that’s not installed on your Android project by calling firebase.messaging() 
  • Solution: happen if you do not add the firebase.messaging()  in your mainApplication.java file.

Something like this, issue name changes.

https://www.itechinsiders.com/ - react native firebase 5
  • Problem: Installed the required Firebase Android SDK dependency 'com.google.firebase:firebase-notifications' in your 'android/app/build.gradle' file.

Solution: It happens if you didn’t add this line

 implementation "com.google.firebase:firebase-messaging:18.0.0" 

You can find my post on medium as well click here please follow me on medium as well.

You can find my next post here.

If have any query/issue, please feel free to ask.

Happy Coding Guys.


Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *