DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Sherlock
Sherlock

Posted on

How to use React Native Push Plugin?

Introduction

Mobile push notifications are notification messages sent by a server to mobile application users. Implementing push notifications has many benefits, such as improving user engagement by informing users about new special offers, products and services, increasing app retention rates of inactive users, tracking user behavior with A/B tests, and more.

Huawei push plugin for React Native enables developers to use Android HMS push kit in React Native applications. The publishers can push the notifications by using Huawei developer console or posting HTTP requests to Huawei push kit, which will send the notifications to the app users accordingly. The diagram below depicts the workflow of Huawei push kit.
Alt Text
Push Plugin Workflow
In this article, I’ll illustrate how to create your project in the Huawei developer console, integrate the plugin, and use it.

Creating Your Project in Huawei Developer Console

Registering a Huawei ID

You need to register a Huawei ID to use the plugin. If you don’t have one, follow the instructions here.

Creating a Huawei App

To create a Huawei App, visit the developer console and authenticate your Huawei ID. Follow the instructions in this tutorial to create an application.

Generating a Signing Certificate Fingerprint

Signing certificate fingerprint is required to authenticate your app to Huawei mobile services. Make sure JDK is installed. To create one, go to JDK directory’s bin folder and open a terminal in this directory. Execute the following command:

keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
Enter fullscreen mode Exit fullscreen mode

This command creates the keystore file in application_project_dir/android/app with the configurations you’ve typed in <…>.

Adding SHA256 Key to the Huawei Project in App Gallery

The next step is obtaining the SHA256, which is needed for authenticating your app to Huawei services, for the keystore file. To obtain it, type the following command in terminal:

keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
Enter fullscreen mode Exit fullscreen mode

After an authentication, the SHA256 key will be revealed as shown below:
Alt Text
Copy the SHA256 key and visit Huawei developer console//General Information. Paste it to the field SHA-256 certificate fingerprint, set the data storage location to Germany.
Alt Text
Finally, enable the push kit from Project Setting/Manage APIs.

You’ve completed configuring your React Native application in App gallery. In the further steps, I’ll explain how to integrate the plugin to your React Native application.

Integrating the Plugin

To integrate the plugin open a terminal in your project directory and type the following command:

npm i @hmscore/react-native-hwpush

Enter fullscreen mode Exit fullscreen mode

After the command is executed, the file tree is supposed to be in the following way:

projectdir
    |_ node_modules
        |_ ...
        |_ @hmscore
            |_react-native-hwpush
            |_ ...
        |_ ...
Enter fullscreen mode Exit fullscreen mode

Then, download the agconnect-services.json file from your push kit project in app gallery from the General Information tab. Place the file in android/app directory in your React Native project

Go to android/app/build.gradle directory in your React Native project. Follow the steps below:
Add the AppGallery Connect plug-in dependency show below to the file header.

apply plugin: 'com.huawei.agconnect'
Enter fullscreen mode Exit fullscreen mode

In android/defaultConfig node, set the value of the field applicationId as the package name you entered in the AppGallery and set minSdkVersion to 19 or higher

defaultConfig {   
  applicationId <package_name_of_the_project_in_app_gallery>   
  minSdkVersion 19   
  ...   
}   
Enter fullscreen mode Exit fullscreen mode

In android/signingConfigs/config node, enter the keystore file credentials.

signingConfigs {   
  config {   
  storeFile file(<keystore_file_name>)   
  storePassword β€˜<store_password>’   
  keyAlias β€˜<alias>’   
  keyPassword β€˜<key_password>’   
  }   
}
Enter fullscreen mode Exit fullscreen mode

Go to android/build.gradle directory in your React Native project. Follow the steps below:

Add maven {url β€˜https://developer.huawei.com/repo/'} to buildscript/repositories and allprojects/repositories.

Add classpath β€˜com.huawei.agconnect:agcp:1.2.1.301’ to buildscript/dependencies.

The file content should look like as below.

buildscript{   
  repositories{   
     google()   
     jcenter()   
     maven {url 'https://developer.huawei.com/repo/'}   
  }   
  dependencies{   
     classpath 'com.huawei.agconnect:agcp:1.2.1.301'   
  }   
}   
allprojects{   
  repositories{   
     google()   
     jcenter()   
     maven {url 'https://developer.huawei.com/repo/'}   
  }   
}
Enter fullscreen mode Exit fullscreen mode

Go to android/settings.gradle and add the following:

include β€˜:react-native-hwpush’   
project(β€˜:react-native-hwpush’).projectDir = new File(rootProject.projectDir, β€˜../node_modules/@hmscore/react-native-hwpush/android’)
Enter fullscreen mode Exit fullscreen mode

You’ve integrated the plugin to your app. In the next section, I’ll explain how to use the plugin.

Using the Plugin

Obtaining a Token

In order to push notifications to a device, you need to obtain a token which is a unique identifier for your test device for push notifications. To get the token, use getToken method of the RNHmsInstanceId module.

import {NativeModules} from 'react-native'   
NativeModules.RNHmsInstanceId.getToken((result, token) => {   
  console.log(JSON.stringify(token));   
});  
Enter fullscreen mode Exit fullscreen mode

Pushing Notification Messages

To push a notification message to your device, go to your Huawei developer console and navigate to your project/Growing/Push Kit/Add notification.
Alt Text
Then fill in the fields, type the token for your device in Device token field. Finally, click submit to push the notification.
Alt Text

Pushing Data Messages

Data messages are the messages with key-value pairs. Unlike the notification messages, they don’t pop notifications. Thus, they must be listened by a NativeEventEmitter. To listen data messages, listen for the event PushMsgReceiverEvent as shown below.

import {EventEmitter} from 'react-native'
let emitter = new NativeEventEmitter();
listener = emitter.addListener('PushMsgReceiverEvent', (event) => {
  console.log(JSON.stringify(event))
});
// call listener.remove() to stop listening data messages
Enter fullscreen mode Exit fullscreen mode

To push a data message, go to the Huawei push console to push a new notification, choose Data Message as the type.

Subscribing to Topics

Subscribing to a topic enables the users to receive data messages by the subscribed topic. To subscribe a topic, use subscribe method of the RNHmsMessaging module. Note that you need to listen the data messages (i.e. listen for the PushMsgReceiverEvent) to receive the topic specific messages.

import {NativeModules} from 'react-native'
NativeModules.RNHmsMessaging.subscribe('myTopic', (result, errinfo) => {
  if (result == RNErrorEnum.SUCCESS) {
    console.log('Subscribed!');
  } else {
    console.log('Failed to subscribe : ' + errinfo);
  }
});
Enter fullscreen mode Exit fullscreen mode

To push a notification or data message by topic, go to the Huawei push console to push a new notification, choose push scope as Subscriber and then select the topic of the message to be sent.
Alt Text

Unsubscribing from Topics

Unsubscribing from a topic lets the user not to listen data messages by the unsubscribed topic. To unsubscribe from a topic, use unsubscribe method of the RNHmsMessaging module.

  import {NativeModules} from 'react-native'
  NativeModules.RNHmsMessaging.unsubscribe("myTopic", (result, errinfo) => {
    if (result == RNErrorEnum.SUCCESS) {
      console.log("Unsubscribed!")
    } else {
      console.log("Failed to unsubscribe : "+errinfo);
    }
  });
Enter fullscreen mode Exit fullscreen mode

Conclusion

HMS React Native push plugin enables you to integrate Huawei push kit for React Native applications. With Huawei push plugin, developers can push notifications to the users for various purposes such as improving app retention, informing users about special offers and news, performing A/B tests to make business decisions, sending data messages to alter app behavior, and more.

Github link: https://github.com/HMS-Core/hms-react-native-plugin/tree/master/react-native-hms-push

You may read further about HMS push kit from the articles in references and leave your questions in comments.

For more details, you can go to:
l official website:https://developer.huawei.com/consumer/en/hms
l Documentation page:https://developer.huawei.com/consumer/en/doc/development
l Reddit to join our developer discussion: https://www.reddit.com/r/HMSCore/
l GitHub:https://github.com/HMS-Core
l Stack Overflow:https://stackoverflow.com/questions/tagged/huawei-mobile-services

Top comments (0)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›