Integrate Huawei Ads Kit into Ionic Project in 10 Mins - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Ads can provide to developers an extensive data capabilities to deliver high quality ad content to their users. By integrating HMS ads kit we can start earning right away. It is very useful particularly when we are publishing a free app and want to earn some money from it.
Integrating HMS ads kit does not take more than 10 mins. HMS ads kit currently offers five types of ad format:
1) Banner Ad
2) Native Ad
3) Reward Ad
4) Interstitial Ad
5) Splash Ad
In this article we are going to learn how to integrate HMS Ads Kit in Ionic application.
Demo
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisite
1) Must have a Huawei Developer Account.
2) Must have a Huawei phone with HMS 4.0.0.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) Must install node in the system
5) Must install Ionic in the system using below command:
Code:
npm install -g [user=1329689]@iONiC[/user]/cli
Things need to be done
1) Generating a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
2) Create an app in the Huawei AppGallery connect.
3) Provide the SHA Key in App Information Section.
4) Provide storage location.
5) Download the agconnect-services.json and store it somewhere on our computer.
6) Create a blank Ionic Project using below command:
Code:
ionic start Your_Application_Name blank --type=angular
7) Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install @hmscore/cordova-plugin-hms-ads
8) If you want full Ionic support with code completion etc., install @iONiC-native/core in your project.
Code:
npm install [user=1329689]@iONiC[/user]-native/core --save-dev
9) Run the following command to copy the ionic/dist/hms-ads folder from library to node_modules @iONiC-native folder under your Ionic project.
Code:
cp node_modules/@hmscore/cordova-plugin-hms-ads/ionic/dist/hms-ads node_modules [user=1329689]@iONiC[/user]-native/ -r
10) Run the following command to compile the project:
Code:
ionic build
npx cap init [appName] [appId]
Where appName is the name of your app, and appId is package_name in your agconnect-services.json file (ex: com.example.app).
11) Run the following command to add android platform to your project:
Code:
ionic capacitor add android
12) Make sure your project has a build.gradle file with a maven repository address and agconnect service dependencies as shown below:
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
14) Add plugin to the build.gradle file in the app directory as show below:
15) Add ads service implementation into to dependencies section of build.gradle file in the app directory as show below:
16) Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below:
17) To update dependencies, and copy any web assets to your project, run the following code:
Code:
npx capacitor sync
Let’s Code
Import
Import the following code in your application page:
Code:
import {
HmsAds, InterstitialAdEvents,
BannerAdOptions, BannerAdEvents, SplashAdEvents,
RewardAdEvents, NativeAdEvents, BannerAdSize, Color, Gender,
NonPersonalizedAd} from [user=1329689]@iONiC[/user]-native/hms-ads/ngx';
Initialization
We need to initialize HMS ads kit as show below:
Code:
async ionViewDidEnter(){
const isInit = await this.hmsads.isInit();
if(!isInit){
await this.hmsads.init({ bannerFloat: false });
}
}
Banner Ads
Banner ads are rectangular images that occupy a spot at the top, middle, or bottom within an app's layout. Banner ads refresh automatically at regular intervals. When a user taps a banner ad, the user is redirected to the advertiser's page in most cases.
Code:
async showBannerAd() {
const options: BannerAdOptions = {
adId: 'testw6vs28auh3',
bannerAdSize: BannerAdSize['BANNER_SIZE_SMART'],
bgColor: Color['TRANSPARENT'],
anchor: 'bottom',
bannerRefresh: 50
}
this.banner = new this.hmsads.Banner;
await this.banner.create(options);
this.banner.on(BannerAdEvents.LOADED, () => {
console.log("bannerAdsInstance :: loaded");
});
this.banner.on(BannerAdEvents.FAILED, () => {
console.log("bannerAdInstance :: failed");
});
await this.banner.loadAd({});
}
Below are the size we can choose to create banner ads:
Native Ad
Native ads fit seamlessly into the surrounding content to match our app design. Such ads can be customized as needed.
Code:
async showNativeAd() {
if (this.nativeAdInstance != null)
await this.nativeAdInstance.destroy();
const template = this.nativeAdSize as "video" ;
const nativeElem = document.getElementById("native-ad-element");
let adId = 'testy63txaom86';
nativeElem.style.height = '300px';
// Create a new native ad with selected template
this.nativeAdInstance = new this.hmsads.Native();
await this.nativeAdInstance.create({
div: 'native-ad-element',
template,
bg: Color.WHITE
});
this.nativeAdInstance.on(NativeAdEvents.NATIVE_AD_LOADED, async () => {
console.log("nativeAdInstance :: loaded");
await this.nativeAdInstance.show();
});
// Load the ad.
this.nativeAdInstance.loadAd({
adId
});
}
We can change the template here to banner, video, small or full.
Reward Ad
Rewarded ads are full-screen video ads that reward users for watching.
Code:
async showRewardAd(){
const reward = new this.hmsads.Reward();
await reward.create({
adId: 'testx9dtjwj8hp',
});
reward.on(RewardAdEvents.LOADED, async () => {
await reward.show();
});
reward.loadAd({});
}
Interstitial Ad
Interstitial ads are full-screen ads that cover the interface of an app. Such ads are displayed when a user starts, pauses, or exits an app, without disrupting the user's experience.
Code:
async showInterstitialAd(){
const interstitial = new this.hmsads.Interstitial()
await interstitial.create({ adId: 'testb4znbuh3n2' })
interstitial.on(InterstitialAdEvents.LOADED, async () => {
await interstitial.show()
})
await interstitial.loadAd({})
console.log("finished.")
}
Splash Ad
Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed.
Code:
async showSplashAd() {
const splash = new this.hmsads.Splash();
await splash.create({
logo: {
copyright: 'Copyright Huawei 2020',
owner: 'Huawei',
anchor: 'bottom',
bg: Color['TRANSPARENT']
}
});
splash.on(SplashAdEvents.LOADED, async () => {
await splash.show();
});
splash.on(SplashAdEvents.DISMISSED, async () => {
console.log("SplashAd dismissed");
await splash.cancel();
await splash.destroy();
})
await splash.load({
adId: 'testq6zq98hecj',
orientation: this.hmsads.Orientation.SCREEN_ORIENTATION_PORTRAIT
});
}
Install Referrer Information
For better support app promotion targeted at Huawei devices, we need install referrer capability for advertisers to track promotion channels and attribute conversions.
Code:
showReferrerDetails(){
this.hmsads.getReferrerDetails(true).then(result => alert(JSON.stringify(result)));
}
Obtaining OAID Information
The OAID information can be used to recommend personalized ads to users and attribute ad conversions.
Code:
showOAIDDetails(){
this.hmsads.getOaidResult().then(result => alert(JSON.stringify(result)));
}
Conclusion
We learn how to integrate HMS Ads Kit in Ionic Project. Feel free to comment, share and like the article. Also you can follow me to get awesome article like this every week.
For more reference
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050437673

Related

Search places by keywords with HMS Site Kit

Hello everyone, in this article series, I will tell you about what is HMS Site Kit and how to use it’s features. With HMS Site Kit, you can basically provide users with easy and reliable access to services to related to locations and places.
With the HMS Site Kit, we can provide them make use of this features while helping users to to discover world quickly;
We can take place suggestions according to the keywords that we have determined,
According to the location of the user’s device, we can search for nearby places,
We can get detailed information about a location,
We can learn the human readable address information of a coordinate point,
We can learn the time period where a coordinate point is found.
In the first article of Site Kit series, I will give you an information about how to setup Site Kit to Android project and how to use Keyword Search.
How to integrate HMS Site Kit to project?
First of all, we need to create a signed Bundle/APK of our project. For this, you can follow the steps which have shown in the picture below.
We can start to creating signature by clicking on the Build->Generate Signed Bundle/APK menu on Android Studio. Then, we can start the process of generating a signed APK by selecting the APK option on screen that comes up.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
By pressing the Create New button on the screen that comes up, we can determine the path, password, key alias and key password values of the .jks file to be created for our application. Informations in the Certificate field is not mandatory.
After clicking OK button, we can continue the APK signing process by entering our password informations.
Then, we can complete the signing process by choosing which version of our application we want to sign such as release and debug, together with the signature versions.
After completing this process, we need to make configurations of this signature file in the build.gradle file at the app level of our application.
Code:
signingConfigs {
release {
storeFile file('SiteKitDemo.jks')
keyAlias 'SiteKitDemo'
keyPassword '****'
storePassword '****'
v1SigningEnabled true
v2SigningEnabled true
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.release
debuggable true
}
}
After performing this process, we can perform the operations related to Gradle synchronization by clicking on the sync now button.
After performing this process, we need to add ‘SHA-256 certificate fingerprint’ value of our application to AppGallery Connect.
We can learn value of ‘SHA-256 certificate fingerprint’ via termianl/CMD. For this, we need to go by terminal to the bin folder under the jre(Java Runtime Environment) installed on our system and run the command below.
Code:
C:\Program Files (x86)\Java\jre1.8.0_251\bin>keytool -list -v -keystore <keystore-path>
We will see a screen output as follows. Here, we need to get the value of SHA256.
We need to add this SHA256 value which we have received to the General Information field in the Project Settings menu on AppGalleryConnect. After performing this process, we can download the agconnect-services.json file.
After performing this process, we need to enable Site Kit service in Manage APIs tab on Project Settings tab.
We need to add agconnect-services.json file which we have downloaded, to under app folder on Android Studio of our project as follows.
After performing this process, we need to add Maven libraries and dependency values on build.gradle files.
First of all, we need to open build.gradle file at the project level and add the lines shown below:
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.61'
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' } // HUAWEI Maven repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
def agcpVersion = "1.3.1.300"
classpath "com.huawei.agconnect:agcp:${agcpVersion}" // HUAWEI agcp plugin
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' } // HUAWEI Maven repository
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
After performing this process, we need to add plugin and dependency values in the build.gradle file at the app level as follows.
Code:
apply plugin: 'com.huawei.agconnect'
...
...
dependencies {
...
def siteKitVersion = "4.0.3.300"
implementation "com.huawei.hms:site:${siteKitVersion}"
}
To prevent HMS SDK from hiding, we need to add following lines of code to proguard-rules.pro file which is located under the app folder.
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
HMS Site Kit — Keyword Search
Thanks to this feature provided by Site Kit, we can search for many places such as tourist attractions, restaurants, schools and hotels by entering information such as keywords, coordinates.
Thanks to the data from this search result, we can easily access many different information about places such as name, address, coordinates, phone numbers, pictures, address details. Within the AddressDetail model, we can easily access information about the address piece by piece through different variables and change the way the address’ notation as we wish.
First of all, after sharing sharing the method what we can search by keyword, we will examine these pieces of code and parameters one by one.
Code:
fun keywordSearch(coordinate: Coordinate, keyword: String, radius: Int,
pageIndex: Int, pageSize: Int, countryCode: String){
val searchService = SearchServiceFactory.create(context,
URLEncoder.encode(
"Your-API-KEY",
"utf-8"))
var request = TextSearchRequest()
request.query = keyword
request.location = coordinate
request.radius = radius
request.pageIndex = pageIndex
request.pageSize = pageSize
request.language = Locale.getDefault().language // Getting system language
request.countryCode = countryCode
searchService.textSearch(request, object: SearchResultListener<TextSearchResponse>{
override fun onSearchError(searchStatus: SearchStatus?) {
Log.e("SITE_KIT","${searchStatus?.errorCode} - ${searchStatus?.errorMessage}")
}
override fun onSearchResult(textSearchResponse: TextSearchResponse?) {
var siteList = textSearchResponse?.sites
siteList?.let {
for(site in siteList){
Log.i("SITE_KIT", "Name => ${site.name}," +
"Format address => ${site.formatAddress}, " +
"Coordinate => ${site.location.lat} - ${site.location.lng}, " +
"Phone => ${site.poi.phone}, " +
"Photo URLS => ${site.poi.photoUrls}, " +
"Rating => ${site.poi.rating}, " +
"Address Detail => ${site.address.thoroughfare}, ${site.address.subLocality}, " +
"${site.address.locality}, ${site.address.adminArea}, ${site.address.country}")
}
} ?: kotlin.run {
Log.e("SITE_KIT","There is not any site")
}
}
})
}
First, we need to create a SearchService object from the SearchServiceFactory class. For this, we can use the create() method of the SearchServiceFactory class. We need to declare two parameters in create() method.
The first of these parameters is context value. It is recommended that Context value should be in Activity type. Otherwise, when HMS Core(APK) needs to be updated, we can not receive any notification about it.
The second parameter is API Key value that we can access via AppGallery Connect. This value is generated automatically by AppGallery Connect when a new app is created. We need to encode API parameter as encodeURI.
We need to create a TextSearchRequest object to perform searching by keyword. We will perform the related search criteria on this TextSearchRequest object.
While performing the searching operation, we can set many different criteria as we see in the code snippet. Let us examine the duties of these criteria one by one if you want to:
Query: Used to specify the keyword that we will use during the search process.
Location: It is used to specify latitude and longitude values with a Coordinate object to ensure that search results are searched as closely to the location that we want.
Radius: It is used to make the search results within in a radius determined in meters. It can take values between 1 and 50000, and its default value is 50000.
CountryCode: It is using to limit search results according to certain country borders.
Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, the language of the query field we have specified in the query field is accepted by default. In example code snippet in above, the language of device has been added automatically in order to get a healthy result.
PageSize: Results return with the Pagination structure. This parameter is used to determine the number of Sites to be found in each page.
PageIndex: It is used to specify the number of the page to be returned with the Pagination structure.
Once we have determined our criteria, we can start the search using textSearch() method of SearchService object. textSearch() method takes two parameters.
First parameter is TextSearchRequest object which we have defined above. Here, our search criterias are defined.
For the second parameter, we need to implement SearchResultListener interface. Since the SearchResultListener interface is generic, we need the data type that results will return here. Here we can specify TextSearchResponse class that is model provided by Huawei Site Kit. This interface contains two methods, onSearchError() and onSearchResult() methods. We can configure these methods according to logic of our program and take necessary actions.

How to Integrate HUAWEI Nearby Plugin to Cordova Project

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
Hello everyone, in this article, I will show how to integrate Huawei Nearby Plugin to a Cordova project.
Prerequisites
You should install npm, Node.js and Cordova CLI on your PC.
Pre-Installation
Configuring App Information in AppGallery Connect
Before you get started, you must register as a HUAWEI developer and complete identity verification on HUAWEI Developers.
Click to expand...
Click to collapse
Firstly, lets create an AppGallery Connect Project.
Sign in to AppGallery Connect and select My projects.
Click Add project.
Enter a project name and click OK.
After the project is created, the Project settings page is displayed. Before you use development capabilities provided by AppGallery Connect, you need to add an app to your project first.
In section Project settings > General information, click Add app.
On the Add app page, enter app information.
On the Project settings page, enter SHA-256 certificate fingerprint and then download the configuration file agconnect-services.json for Android platform.
A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in the AppGallery Connect. You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial for the certificate generation. Perform the following steps after you have generated the certificate.
Click to expand...
Click to collapse
Enabling Service
To use HUAWEI Nearby Service on your app, you first need to enable the service.
Sign in to HUAWEI Developers and click Console in the upper right corner. Go to HMS API Services > My APIs, select the project for which you want to enable HUAWEI Nearby Service, and click Add API from library. The API Library page is displayed.
Click Nearby Service.
On the Nearby Service page, click Enable to enable HUAWEI Nearby Service.
Sign the HUAWEI Nearby Service Agreement.
When you click My projects on the home page of AppGallery Connect to create a project for the first time, a dialog box will be displayed to prompt you to sign the HUAWEI Nearby Service Agreement (for details, please refer to AppGallery Connect Service and Agreement). If you have agreed to the HUAWEI Nearby Service Agreement, no such a dialog box will be displayed after you click Enable. For details, please refer to AppGallery Connect Agreement Signing Guide.
Click to expand...
Click to collapse
Go to HMS API Services > My APIs. The Nearby Service API is displayed.
Pre-installation steps end here. Basically, we created an AppGallery Connect project and enabled the Nearby Service. We also saved the SHA-256 certificate fingerprint to the project.
Installation
Firstly, open a command line and create a new Cordova project.
Bash:
cordova create HMSNearbyDemo com.huawei.medium.nearbydemo HMSNearby
This command will create a new directory named as HMSNearbyDemo and a new project named as HMSNearby inside it. You can change names as you wish.
The widget id property in config.xml file must be same with client > package_name value in agconnect-services.json file.
Click to expand...
Click to collapse
Go to project directory and add the android platform to the project.
Bash:
cd HMSNearbyDemo
cordova platform add android
Now, you need to add Huawei Nearby Plugin to the project. Run the following command in the root directory of your project to install it through npm.
Bash:
cordova plugin add @hmscore/cordova-plugin-hms-nearby
Copy agconnect-services.json file to <project_root>/platforms/android/app directory. In our case, project_root is HMSNearbyDemo folder.
Add keystore(.jks) to your project’s root directory.
You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial page for generating keystore file.
Click to expand...
Click to collapse
Create a file named as build.json in project’s root directory and fill the file according to your keystore information as in example below.
JSON:
{
"android": {
"debug": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
},
"release": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
}
}
}
Huawei Nearby Plugin requires minimum sdk version 21. If your minimum sdk version is lower than 21, set it as 21 in config.xml file. Otherwise, you can skip this step.
XML:
...
<platform name="android">
...
<preference name="android-minSdkVersion" value="21" />
</platform>
Finally, build the project.
Bash:
cordova build android
Using Huawei Cordova Nearby Plugin
Initially, we should request missing permissions from the user.
JavaScript:
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
// ...
// we have requested all permissions.
HMSNearby.requestPermissions([
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH,
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH_ADMIN,
HMSNearby.HMSPermission.PERMISSION_ACCESS_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_CHANGE_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_ACCESS_COARSE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_ACCESS_FINE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_READ_EXTERNAL_STORAGE,
HMSNearby.HMSPermission.PERMISSION_WRITE_EXTERNAL_STORAGE
]).then((res) => {
console.log("Request permissions result: " + res);
});
}
};
Now, all functionalities are ready to use. The Nearby Connection basic structure is shown in the image below. I will show you sample code parts for each step.
Starting Broadcasting
The sample code for starting broadcasting is as follows:
JavaScript:
async function startBroadcasting() {
try {
const name = 'NearbyBroadcast';
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startBroadcasting(name, serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
You can customize the name parameter.
Starting Scanning
The sample code for starting scanning is as follows:
JavaScript:
// starting scanning
async function startScan() {
try {
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startScan(serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
We need to register scan events. When a remote device is found or an already found device is lost, scan events will be triggered.
Registering Scan Events and Requesting Connection
Code part below sends a connection request to the remote device without asking the user when any device is found.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_FOUND, async (res) => {
console.log('listener :: EVENT_SCAN_ON_FOUND triggered: ' + JSON.stringify(res));
// request connect
const resRequest = await HMSNearby.requestConnect("NearbyScan", res.endpointId);
console.log("listener :: requestConnect: " + JSON.stringify(resRequest));
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_LOST, (res) => {
console.log('listener :: EVENT_SCAN_ON_LOST triggered: ' + JSON.stringify(res));
});
Registering Connection Events and Accepting Connection
When a connection established, both peers must accept the connection. Then, event EVENT_CONNECTION_ON_RESULT will be triggered with the success state.
JavaScript:
// registering connection events and accepting connection
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_ESTABLISH, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_ESTABLISH triggered: ' + JSON.stringify(res));
// Accept the connection request without notifying user.
HMSNearby.acceptConnect(res.endpointId);
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_RESULT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_RESULT triggered: ' + JSON.stringify(res));
if (res.statusCode == HMSNearby.StatusCode.STATUS_SUCCESS) {
// The connection was established successfully, we can exchange data.
}
});
Registering Data Events and Sending Data
We connected to remote peer successfully. Now, we can send any data to peer.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_RECEIVED, (res) => {
console.log('listener :: EVENT_DATA_ON_RECEIVED triggered');
if (res.dataType === HMSNearby.DataType.DATA_BYTES) {
const receivedBytes = res.data;
// data as number array
}
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_TRANSFER_UPDATE, async (res) => {
console.log('listener :: EVENT_DATA_ON_TRANSFER_UPDATE triggered: ' + JSON.stringify(res));
if (res.status === HMSNearby.TransferState.TRANSFER_STATE_SUCCESS) {
console.log('listener :: data transfer success');
}
});
try {
const bytes = [11, 22, 33, 44]; // any data in number array
const endpointIds = ['endpointId1', 'endpointId2']; // remote endpoint id list
await HMSNearby.sendBytes(bytes, endpointIds);
} catch(ex) {
alert(JSON.stringify(ex));
}
Disconnection
After all operations are done, we should simply call disconnect method. When a peer calls disconnect, event EVENT_CONNECTION_ON_DISCONNECT will be triggered on the other peer’s device.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_DISCONNECT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_DISCONNECT triggered: ' + JSON.stringify(res));
});
async function disconnect() {
try {
const endpointId = 'endpointId';
await HMSNearby.disconnect(endpointId);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
Conclusion
In this article, I integrated HMS Nearby Plugin to a Cordova project and showed the basic functionalities of Nearby Connection. I tried to explain connecting to peer, transferring data and disconnection functionalities with examples.
Thank you for reading, I hope it was helpful.

Beginner: Ads Alert! Integration of Huawei Ads Kit in Application using React Native

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to integrate Huawei Ads Kit in an Application using React Native. I will be using Interstitial Ads. Interstitial ads are full-screen ads that cover the interface of an app. Such an ad is displayed when a user starts, pauses or exits an app, without disrupting the user's experience.
Ads Kit
Huawei Ads Kit leverages the vast user base of Huawei devices and Huawei's extensive data capabilities to provide you with the Publisher Service, helping you to monetize traffic.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Interstitial Ads in this application.
Requirements
1. JDK version: 1.7 or later
2. Android Studio version: 3.X or later
3. minSdkVersion: 21 or later
4. targetSdkVersion: 31 (recommended)
5. compileSdkVersion: 29 (recommended)
6. Gradle: 4.1 or later (recommended)
7. Must have a Huawei Developer Account
8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
9. React Native environment with Android Studio, Node Js and Visual Studio code.
Major Dependencies
React Native CLI : 2.0.1
React Native Ads Kit SDK : 4.0.4
React-native-hms-ads gradle dependency.
Preparation
In order to develop the HMS react native apps, following steps are mandatory:
1. Create an app or project in the Huawei AppGallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project. Use the following command
Code:
react-native init project name
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
5. Run below command under project directory using CLI if you cannot find node modules.
npm install & npm link
Integration
Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“: react-native-hms-ads”)
Linking the HMS Ads Kit Sdk
Run below command in the project directory
Code:
react-native link react-native-hms-ads
Adding permissions
Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sync Gradle.
Development
To successfully run interstitial ads in application, we would need to:
Creating an Interstitial Ad.
Setting Ad Slot ID.
Loading the Ad.
Displaying the Ad.
Listening for Ad Events
Creating an Interstitial Ad
JavaScript:
HMSInterstitial module is used to create the interstitial Ad
import HMSAds, {
HMSInterstitial,
InterstitialMediaTypes,
} from 'react-native-hms-ads';
Setting Ad Slot ID
JavaScript:
setAdId() method is responsible for setting the Ad Slot. Below is the code for same. Refer this article to know the process for creating the slot Id’s.
// creating object for the Ad Slot ID
const Interstitial = () => {
let interstitialAdIds = {};
interstitialAdIds[InterstitialMediaTypes.IMAGE] = 'teste9ih9j0rc3';
interstitialAdIds[InterstitialMediaTypes.VIDEO] = 'testb4znbuh3n2';
}
// creating object for setting up the media type for the ad
const [displayForm, setDisplayForm] = useState({
mediaType: InterstitialMediaTypes.VIDEO,
adId: interstitialAdIds.video,
})
// setting up the ID
HMSInterstitial.setAdId(displayForm.adId);
Setting Ad Request Parameters
JavaScript:
setAsParam() method is used to set the parameters for the specific ad audience. Below code is called on the button click for the same.
import {ContentClassification,UnderAge } from 'react-native-hms-ads';
HMSInterstitial.setAdParam({
adContentClassification:
ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
// appCountry: '',
// appLang: '',
// belongCountryCode: '',
gender: Gender.UNKNOWN,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
// requestOrigin: '',
tagForChildProtection:
TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
// targetingContentUrl: '',
});
Loading the Ad
Calling the loadAd() method to load the ad on button click.
JavaScript:
HMSInterstitial.loadAd()
Displaying the Ad
isLoaded() method is called to confirm if the ad has finished loading. Once ad loading is completed, show() method is called to display the ad on a button click.
JavaScript:
setLoaded(false);
HMSInterstitial.show();
Listening for Ad Events
As we handle multiple Ad events for different actions, Listener can be added for listening to these events as below.
JavaScript:
useEffect(() => {
HMSInterstitial.setAdId(displayForm.adId);
HMSInterstitial.adClosedListenerAdd(() => {
toast('HMSInterstitial adClosed');
});
// HMSInterstitial.adClosedListenerRemove();
HMSInterstitial.adFailedListenerAdd((error) => {
toast('HMSInterstitial adFailed');
console.warn('HMSInterstitial adFailed, error: ', error);
});
// HMSInterstitial.adFailedListenerRemove();
HMSInterstitial.adLeaveListenerAdd(() => {
toast('HMSInterstitial adLeave');
});
// HMSInterstitial.adLeaveListenerRemove();
HMSInterstitial.adOpenedListenerAdd(() => {
toast('HMSInterstitial adOpened');
});
// HMSInterstitial.adOpenedListenerRemove();
HMSInterstitial.adLoadedListenerAdd((result) => {
toast('HMSInterstitial adLoaded');
console.log('HMSInterstitial adLoaded, result: ', result);
});
// HMSInterstitial.adLoadedListenerRemove();
HMSInterstitial.adClickedListenerAdd(() => {
toast('HMSInterstitial adClicked');
});
// HMSInterstitial.adClickedListenerRemove();
HMSInterstitial.adImpressionListenerAdd(() => {
toast('HMSInterstitial adImpression');
});
// HMSInterstitial.adImpressionListenerRemove();
return HMSInterstitial.allListenersRemove;
})
Add all these functionalities to a button according to your UI.
For example, in a News Application if there is a button names “Sports” then:
JavaScript:
<Button
title="Sports"
onPress={() => {
HMSInterstitial.setAdParam({ …})
HMSInterstitial.loadAd();
setLoaded(false);
HMSInterstitial.show();
}}
/>
Testing
Run the below command to build the project
Code:
React-native run-android
Run the application (Generating the Signed Apk):
Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. agconnect-services.json is not required for integrating the hms-ads-sdk.
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.
Code:
gradlew clean
Conclusion
In this article, we can learn about how to integrate Ads Kit and how to add Interstitial ad in React native project. It provides developers different capabilities to deliver good quality ads content to users.
Reference
Ads Kit: Documentation
Ads Kit: Training Video

Splash season is on! Integration of Huawei Ads Kit (Splash Ads) in Application using React Native

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to integrate Huawei Ads Kit in an Application using React Native. I will be using Splash Ads. Huawei Ads kit offers Splash Ad to use in the business to achieve certain business and advertisement goals by following the digital marketing practices.
Ads Kit
Huawei Ads Kit leverages the vast user base of Huawei devices and Huawei's extensive data capabilities to provide you with the Publisher Service, helping you to monetize traffic.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Splash Ads in this application.
Requirements
1. JDK version: 1.7 or later
2. Android Studio version: 3.X or later
3. minSdkVersion: 21 or later
4. targetSdkVersion: 31 (recommended)
5. compileSdkVersion: 29 (recommended)
6. Gradle: 4.1 or later (recommended)
7. Must have a Huawei Developer Account
8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
9. React Native environment with Android Studio, Node JS and Visual Studio code.
Major Dependencies
React Native CLI : 2.0.1
React Native Ads Kit SDK : 4.0.4
React-native-hms-ads gradle dependency.
Preparation
In order to develop the HMS react native apps, following steps are mandatory:
1. Create an app or project in the Huawei AppGallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project. Use the following command
Code:
react-native init project name
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
5. Run below command under project directory using CLI if you cannot find node modules.
Code:
npm install & npm link
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Ads Kit Sdk
Run below command in the project directory
Code:
react-native link react-native-hms-ads
5. Adding permissions
Add below permissions to Android.manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sync Gradle.
Development
To successfully run Splash ads in application, we would need to:
Creating an Splash Ad.
Setting Ad Slot ID.
Customizing Screen
Loading the Ad.
Displaying the Ad.
Listening for Ad Events
Creating an Splash Ad
Splash ad components can be added to an app by importing the HMSSplash module. The following sample code shows how to use the class to add a splash ad component:
Code:
import {HMSSplash} from '@hmscore/react-native-hms-ads';
Setting Ad Slot ID
Code:
setAdId() method is responsible for setting the Ad Slot. Call the setAdId() method to set an ad slot ID. Below is the code for same.
// creating object for the Ad Slot ID
const Splash = () => {
let SplashAdIds = {};
SplashAdIds[SplashMediaTypes.IMAGE] = 'teste9ih9j0rc3';
SplashAdIds[SplashMediaTypes.VIDEO] = 'testb4znbuh3n2';
}
// creating object for setting up the media type for the ad
const [displayForm, setDisplayForm] = useState({
mediaType: SplashMediaTypes.VIDEO,
adId: SplashAdIds.video,
})
// setting up the ID
HMSSplash.setAdId(displayForm.adId);
Customizing a Screen
Some parts of the splash ad screen can be customized. Slogan images, logos, and text can be defined before the ad is displayed.
Code:
HMSSplash.setLogoText('HMS App')
.then(res=>console.log(res));
HMSSplash.setCopyrightText('Copyright HMS')
.then(res=>console.log(res));
//add logo,slogan,wide_slogan in res/drawable folder according to your need and preference.
HMSSplash.setLogoResource("logo")
.then(res=>console.log(res));
HMSSplash.setSloganResource("slogan") .then(res=>console.log(res));
HMSSplash.setWideSloganResource("wide_slogan")
.then(res=>console.log(res));
Setting Ad Request Parameters
setAsParam() method is used to set the parameters for the specific ad audience. Below code is called on the button click for the same.
Code:
import {ContentClassification,UnderAge } from 'react-native-hms-ads';
HMSSplash.setAdParam({
adContentClassification:
ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
// appCountry: '',
// appLang: '',
// belongCountryCode: '',
gender: Gender.UNKNOWN,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
// requestOrigin: '',
tagForChildProtection:
TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
// targetingContentUrl: '',
});
Displaying the Ad
Call the show() method to display the ad. The sample code is as follows:
Code:
HMSSplash.show()
.then(res=>console.log(res));
Listen to Ad Events
Listener functions can be triggered with the different ad actions and associated events.
Code:
HMSSplash.adLoadedListenerAdd(() => {
toast('HMSSplash adLoaded');
});
// HMSSplash.adLoadedListenerRemove();
HMSSplash.adFailedToLoadListenerAdd(() => {
toast('HMSSplash adFailedToLoad');
});
// HMSSplash.adFailedToLoadListenerRemove();
HMSSplash.adDismissedListenerAdd(() => {
toast('HMSSplash adDismissed');
});
// HMSSplash.adDismissedListenerRemove();
HMSSplash.adShowedListenerAdd(() => {
toast('HMSSplash adShowed');
});
// HMSSplash.adShowedListenerRemove();
HMSSplash.adClickListenerAdd(() => {
toast('HMSSplash adClick');
});
Just in case you want to add a video to your splash screen in an application you can use:
var navigator = this.props.navigator;
setTimeout (() => {
navigator.replace({
component: LoginScreen,
// <-- This is the View you go to
});
}, 5000); //<-- Time until it jumps to "MainView"
}
render () {
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center',width:null,height:null}}>
<Video source={require('./images/splashVideo.mp4')}
style={{position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
opacity: 0.3}}
muted={true}
repeat={true}
resizeMode="cover"
 />
<View>{StatusBar.setBackgroundColor('black', true)}</View>
{/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/}
</View>
);
}
Testing
Run the below command to build the project
Code:
React-native run-android
Result
Tips and Tricks
1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
2. agconnect-services.json is not required for integrating the hms-ads-sdk.
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.
Code:
gradlew clean
Conclusion
In this article, we can learn about how to integrate Ads Kit and how to add Splash ad in React native project. It provides developers different capabilities to deliver good quality ads content to users.
Reference
Ads Kit: Documentation
Ads Kit: Training Video

Know the latest weather! Integration of Huawei Push Kit in Application using React Native

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to subscribe the topic using integrating the Huawei Push Kit into React Native project.
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 or directly from the AppGallery Push Kit 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
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Push Kit.
9. Environment set up, refer below link
https://reactnative.dev/docs/environment-setup
10. Create project using below command
Code:
react-native init projectname
11. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
12. Integrate the Hmspush plugin
Code:
npm i @hmscore/react-native-hms-push
13. Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
14. Add to dependencies.
Code:
Implementation project (': react-native-hms-push)
15. Project level build.gradle/buildScript directory set minSdkVersion to 19 or higher higher. In android/signingConfigs/config node, enter the keystore file credentials.
Code:
signingConfigs {
config {
storeFile file(<keystore_file_name>)
storePassword ‘<store_password>’
keyAlias ‘<alias>’
keyPassword ‘<key_password>’
}
}
16. Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
-Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
-Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
17. Navigate to android/settings.gradle and add the following.
Code:
include ':react-native-hms-push'
project(':react-native-hms-push').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-push/android')
18. Add below permissions in Android.manifest file.
Code:
<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.
Code:
HmsPushInstanceId.getToken("")
.then((result) => {
this.log("getToken", result);
})
.catch((err) => {
alert("[getToken] Error/Exception: " + JSON.stringify(err));
});
Enabling/Disabling the message receiving
HmsPushMessaging.turnOnPush()
.then((result) => {
this.log("turnOnPush", result);
})
.catch((err) => {
This.log("[turnOnPush] Error/Exception: " + JSON.stringify(err));
});
Code:
HmsPushMessaging.turnOffPush()
.then((result) => {
this.log("turnOffPush", result);
})
.catch((err) => {
This.log("[turnOffPush] 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.
Receiving the data messages
The data messages are not displayed directly on user devices. They have a data payload in a key-value pair. The data messages pushed by the server can be listened to by onRemoteMessageReceived() encapsulated in HmsPushEvent. The data message listener should be registered in componentDidMount() of Component to be used.
Code:
componentDidMount() {
this.listener = HmsPushEvent.onRemoteMessageReceived(event => {
const RNRemoteMessageObj = new RNRemoteMessage(event.msg);
const msg = RNRemoteMessageObj.parseMsgAllAttribute(event.msg);
console.log("Data message received : " + msg);
})}
Performing automatic Initialization.
Code:
HmsPushMessaging.setAutoInitEnabled(true)
.then((result) => {
this.log("setAutoInitEnabled", result);
})
.catch((err) => {
This.log("[setAutoInitEnabled] Error/Exception: " + JSON.stringify(err));
});
User can also send local notification messages.
Add the following code in AndroidManifest.xml :
Code:
<application ...>
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationActionsReceiver" />
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="com.huawei.hms.rn.push.receiver.HmsLocalNotificationScheduledPublisher"
android:enabled="true"
android:exported="true">
</receiver>
</application>
Modify and add following code according to need:
Code:
import { HmsLocalNotification } from'@hmscore/react-native-hms-push';
const notification = {
[HmsLocalNotification.Attr.title]: ‘Title of Notification',
[HmsLocalNotification.Attr.message]: 'Message is important', // (required)
[HmsLocalNotification.Attr.largeIcon]: 'ic_launcher',
[HmsLocalNotification.Attr.smallIcon]: 'ic_notification',
[HmsLocalNotification.Attr.bigText]: ‘bigText says HI',
[HmsLocalNotification.Attr.subText]: 'subText says hi',
[HmsLocalNotification.Attr.color]: 'black',
[HmsLocalNotification.Attr.vibrate]: false,
[HmsLocalNotification.Attr.vibrateDuration]: 1000,
[HmsLocalNotification.Attr.tag]: 'hms_tag',
[HmsLocalNotification.Attr.ongoing]: false,
[HmsLocalNotification.Attr.importance]: HmsLocalNotification.Importance.max,
[HmsLocalNotification.Attr.dontNotifyInForeground]: false,
[HmsLocalNotification.Attr.autoCancel]: false,
[HmsLocalNotification.Attr.actions]: '["Yes", "No"]'
};
// LocalNotification
HmsLocalNotification.localNotification(notification)
.then((result) => {
this.log("LocalNotification Default", result);
})
.catch((err) => {
This.log(
"[LocalNotification Default] Error/Exception: " + JSON.stringify(err)
);
});
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
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. Make sure you import:
import {HmsPushMessaging} from'@hmscore/react-native-hms-push';
6. 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 in React native project. It offers reliable, responsive and precise push service. It helps the app to react to a wide range of usage scenarios, dramatically boosting user engagement.
Reference
Push Kit: Documentation
Push Kit: Codelab
Push Kit: Training Video

Categories

Resources