Push notifications in React-native android app using FCM

Mobile AppReact native
Push notifications in React-native android app using FCM

For a successful mobile app, push notifications are very essential. It keeps the app live and boosts app usage and traffic. Push notifications can keep users updated and give app admin a way to send notification easily to end users and keep them updated. For a beginner, it is always a bit tricky to set up. Sometimes version mismatches could create a lot of error while developing. This article will show step by step implementation of FCM (Firebase Cloud Messaging) notifications to a React-native app.

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution from Google that lets us deliver messages to devices.

First of all, let’s start with a new react native app using the following command. We are not going to all details of setting up the platform for this and believe you have it covered already.

create-react-nataive-pp reactFcm

After the project is created, we have to eject the app to continue the process. As we have to add FCM plugin, we need to modify android core project files to make it work. Eject process will generate the required files to the project. We can eject the app using the following command.

npm run eject

Ejection process will ask for project name which should appear on project files. Enter the required information and complete the ejection process.

Before we start adding FCM plugin, we need to check the versions of our project and android SDK versions. There are some compatibility issues with older versions of react native, matching version details can be found on this link – https://github.com/react-community/create-react-native-app/blob/master/VERSIONS.md

For this tutorial, we are using react native 0.52.x and android sdk 25.0.0. If you are using any other version of react native, please make sure to use compatible versions of Android SDK that is available in the system.

Check/change following on the file app/build.gradle file

compileSdkVersion 25
buildToolsVersion "25.0.0"
compile "com.android.support:appcompat-v7:25.0.0"

 

Run the app after, to make sure everything works as expected.

Now we can add the FCM plugin to the app by running following command.

npm install react-native-fcm --save

After installing the package, run below command to link to react native app

react-native link react-native-fcm

Edit android/build.gradle file as following

dependencies {

   classpath 'com.android.tools.build:gradle:2.0.0'

+   classpath 'com.google.gms:google-services:3.0.0'

 

Edit android/app/build.gradle and add following to the beginning of the file and remaining to required positions

apply plugin: "com.android.application"
+ apply plugin: 'com.google.gms.google-services'

…

dependencies {
+    compile project(':react-native-fcm')
+    compile 'com.google.firebase:firebase-core:10.0.1' //this decides your firebase SDK version
     compile fileTree(dir: "libs", include: ["*.jar"])
     compile "com.android.support:appcompat-v7:23.0.1"
     compile "com.facebook.react:react-native:+"  // From node_modules
 }

 

Edit android/app/src/main/AndroidManifest.xml:

<application
    ...
    android:theme="@style/AppTheme">
 
+   <service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
+     <intent-filter>
+       <action android:name="com.google.firebase.MESSAGING_EVENT"/>
+     </intent-filter>
+   </service>
 
+   <service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
+     <intent-filter>
+       <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
+     </intent-filter>
+   </service>

…

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:windowSoftInputMode="adjustResize"
+   android:launchMode="singleTop"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
    <intent-filter>

 

After the above steps completed, we need to create a new project in firebase. Login to firebase  (https://console.firebase.google.com) using your Google account.

Click the ‘add project’ button to create a new project in firebase.

 

 

 

 

 

 

 

 

 

Enter the name of your project and click ‘create project’

 

 

 

 

 

 

 

 

 

 

 

 

 

Go to project settings by clicking the gear icon next to menu called ‘project overview’

 

 

 

 

 

 

 

 

 

 

 

 

 

In the general tab, click ‘add app’ button and create a new app. In the form, make sure the package name you are using is the same from our project.

 

 

 

 

 

 

 

 

 

 

 

Click ‘register app’ and in the next window, download the ‘google-services.json’ file to the directory ‘android/app’.

Done! After these steps, we have successfully completed all the required steps for the integration. Now we can add code to our project to handle notifications in our app.

First, create a file to declare global variables

app/FirebaseConstants.js

const FirebaseConstants = {
	KEY: "YOUR_API_KEY"
}

export default FirebaseConstants;

 

‘YOUR_API_KEY’ Must be replaced with app’s API key, which we can get from firebase console by going to ‘cloud messaging’ tab in the firebase console and copy the ‘Sender ID’.

 

 

 

 

 

 

 

 

 

 

 

Add following code to the root file of your react native project (app.js/index.andoid.js) to register for push notifications.

import FCM, {NotificationActionType} from "react-native-fcm";
import firebaseClient from  "./FirebaseClient";

class MainPage extends Component {
  constructor(props) {
    super(props);

    this.state = {
      token: "",
      tokenCopyFeedback: ""
    }
  }

  async componentDidMount(){
try{
      let result = await FCM.requestPermissions({badge: false, sound: true, alert: true});
    } catch(e){
      console.error(e);
    }

    FCM.getFCMToken().then(token => {
      console.log("TOKEN (getFCMToken)", token);
      this.setState({token: token || ""})
    });
  }}

Save the generated token to send push notifications to the device

Now we need to handle the push notifications to show up in our application. Initiate following code in the file to handle incoming push notifications.

import { Platform, AsyncStorage, AppState } from 'react-native';

import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType, NotificationActionType, NotificationActionOption, NotificationCategoryOption} from "react-native-fcm";

export function registerAppListener(navigation){
  FCM.on(FCMEvent.Notification, notif => {
    console.log("Notification", notif);

    if(Platform.OS ==='android' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification){
      // this notification is only to decide if you want to show the notification when user if in foreground.
      // usually you can ignore it. just decide to show or not.
      notif.finish(WillPresentNotificationResult.All)
      return;
    }

    if(notif.opened_from_tray){
      if(notif.targetScreen === 'detail'){
        setTimeout(()=>{
          navigation.navigate('Detail')
        }, 500)
      }
      setTimeout(()=>{
        alert(`User tapped notification\n${JSON.stringify(notif)}`)
      }, 500)
    }

}

That’s it. We successfully added basic functions to the app to run push notifications. Please note that push notifications only work on real devices. So, we need to run the app in the connected device using the following command

npm run android

Refer the following repo for more details about the plugin and more sample codes.

https://github.com/evollu/react-native-fcm

To send a notification to the app, we can use the following sample code in PHP.

public function fcm($title, $message, $type, $notification_ids =array()){
        define( 'API_ACCESS_KEY', 'Your_api_key');
        $registrationIds = $notification_ids;
        
        $msg = array
            ( 
                'title'         => $title,
                'message'       => $message,
                'summaryText'   => 'The internet is built on cat pictures',
                'click_action'  => 'FCM_PLUGIN_ACTIVITY',
                'vibrate'       => 1,
                'sound'         => 1,
                'type'          => $type
            );
     
        $fields = array
        (
            'registration_ids'  => $registrationIds,
            'data'              => $msg
           
        );
         
        $headers = array
        (
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );
         
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );
        echo $result;
}

Replace ‘Your_api_key’ with ‘Legacy server key’  from firebase console – ‘cloud messaging’ tab.

$registrationIds are the token we generated and saved from the app when register to push notification.

Related Article: Push notifications in the Ionic android mobile app using FCM
                         How to setup Firebase Push Notifications in react native applications?

If you need any help with implementing push notifications in your React-Native apps please contact us.

 

 

 

 

Comments are closed.

2hats Logic HelpBot