Read the latest news! Integration of Huawei Push Kit in Application using React Native
Tags: reactnative, javascript, huaweipushkit, beginners
Published: 2022-03-23 07:24:33

## **Introduction**
In this article, I will explain how to subscribe the topic using integrating the Huawei Push Kit into React Native project. React Native is a tool announced and open-sourced by Facebook in April 2015. It is a cross-platform mobile app development framework that is derived from Facebook's earlier open-source JavaScript framework React. It helps to adapt to native mobile app platforms.

## **Push Kit**
Push notifications offers a great way to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application. Push Kit supports two types of messages: notification messages and data messages. You can send notifications and data messages to your users from your server using the [Push Kit APIs](https://developer.huawei.com/consumer/en/doc/development/HMS-3-References/push-server-send) or directly from the [AppGallery Push Kit Console](https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/push-console).

## **Requirements**
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.300 or later.
3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
4. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.

## **Integrate HMS Dependencies and React Native Project Preparation**

- 
First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a [Huawei ID](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148).

- 
 Create a project in android studio, refer Creating an Android Studio Project.

- 
Generate a SHA-256 certificate fingerprint.

- 
To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > [SHA256 code](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#3).
Or use cmd as explained in SHA256 CODE

- 
 [Create an App in AppGallery Connect](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0).

- 
Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mk2yp5ij8w6kv1df5x9e.png)

- 
 Enter SHA-256 certificate fingerprint and click Save, as follows.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tn75hmvmafqumz0a56c.png)

- 
 Click Manage APIs tab and enable Push Kit.

- 
 Environment set up, refer below link  
https://reactnative.dev/docs/environment-setup

- 
 Create project using below command

`react-native init projectname`

- 
 You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.

`npm install –g react-native-cli`

- 
 Integrate the Hmspush plugin 
 
`npm i @hmscore/react-native-hms-push`

- 
 Add the AGC Plugin dependency.

`apply plugin: 'com.huawei.agconnect'`

- 
 Add to dependencies.

`Implementation project (': react-native-hms-push)`

- 
 Project level build.gradle/buildScript directory set minSdkVersion to 19 or higher higher. 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>’   
  }   
}
```

- 
 Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
-Add to buildscript/repositories

```
maven {url 'http://developer.huawei.com/repo/'}
```
 -Add to buildscript/dependencies

```
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
```

- 
 Navigate to android/settings.gradle and add the following.

```
include ':react-native-hms-push'
project(':react-native-hms-push').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-push/android')
```

- 
 Add below permissions in Android.manifest file.
 

```
<uses-permission android:name="android.permission.WAKE_LOCK" />
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
```

## **Development** 

- 
	Obtain a Token:
 In order to push notifications to a device, you need to obtain a token. To get the token, use getToken method from 

```
HmsPushInstanceId module.
HmsPushInstanceId.getToken("")
      .then((result) => {
        this.log("getToken", result);
      })
      .catch((err) => {
        alert("[getToken] Error/Exception: " + JSON.stringify(err));
      });
```

- 
	Add Push Notifications
To push a notification message to your device, navigate to your Huawei developer console and choose **Project>Growing>Push Kit>Add notification**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bls8nixeoy7mcze69u0w.png)
 

- 
	Subscribing the Topics
Subscribing to a topic enables the users to receive data messages by the subscribed topic. To subscribe a topic, use subscribe method from HmsPushMessaging module.

```
subscribe() {
    HmsPushMessaging.subscribe(this.state.topic)
      .then((result) => {
        this.log("subscribe", result);
      })
      .catch((err) => {
        alert("[subscribe] Error/Exception: " + JSON.stringify(err));
      });
  }
```
To push a notification or data message by topic, navigate 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.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngypga9pl58m68kjdbdt.png)


- 
	Unsubscribe the 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 HmsPushMessaging module.

 

```
unsubscribe() {
    HmsPushMessaging.unsubscribe(this.state.topic)
      .then((result) => {
        this.log("unsubscribe", result);
      })
      .catch((err) => {
        alert("[unsubscribe] Error/Exception: " + JSON.stringify(err));
      });
  }
```

- 
 Run the application (Generating the Signed Apk):
(i) Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
`gradlew assembleRelease`


## **Result**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9clwwdofjtx8q9w68qyq.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4vert9be5cgi1n2hhgo.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06yt5wcswy1ih8nz9hsc.png)
  

## **Tips and Tricks**
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. Make sure you have added the agconnect-services.json file to app folder.
3. Make sure you have added SHA-256 fingerprint without fail.
4. Make sure all the dependencies are added properly.
5. For project cleaning navigate to android directory and run the below command.
`gradlew clean`

## **Conclusion**
In this article, we can learn about how to integrate Push Kit and how to subscribe the topic in React native project. It will guide you to increase your application’s user engagement and boost your retention rates by sending meaningful messages or by informing users about your application.
Reference
Push Kit: [Documentation](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/service-introduction-0000001050040060)
Push Kit:[ Training Video](https://developer.huawei.com/consumer/en/training/course/video/101583005582480166)