{
"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, we will learn added to implement Remote Configuration service provided by Huawei. Remote Configuration is a cloud service where the behavior or features of an app can be changed remotely without having to publish an app update.
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.
Integration process
1. Create a react native project using below command:
Code:
react-native init RemoteConfigReact
2. Generate a Signature File. First navigate to bin folder of java, then enter following command:
Code:
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.
This command creates the keystore file in application_project_dir/android/app.
3. Now generate SHA 256 key by following command.
Code:
keytool -list -v -keystore <keystore-file path>
4. Create an app in App Gallery by following instructions in Creating an AppGallery Connect Project and Adding an App to the Project. Provide the generated SHA256 Key in App Information Section.
5. Download the Huawei Remote config plugin by following command.
Code:
npm i @react-native-agconnect/remoteconfig.
6. Open react native project in Visual studio code.
7. Navigate to android > build.gradle and paste the below maven url inside the repositories of build script and all projects.
Code:
maven { url 'http://developer.huawei.com/repo/' }
And paste the following under dependencies.
Code:
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
8. Open build.gradle file which is located under the project.dir > android > app directory. Configure following dependency.
Code:
implementation project(': react-native-agconnect-remoteconfig')
Also add apply plugin:
Code:
'com.huawei.agconnect'
in app build.gradle file.
9. Add the below lines under signingConfigs in app build.gradle.
Code:
release {
storeFile file(‘<keystore_filename.jks>’)
storePassword '<store_password>'
keyAlias '<alias key name>'
keyPassword '<alias_password>
}
10. Navigate to Project settings and download the agconnect-services. json file and paste it inside android > app
11. Add the following lines to the android/settings.gradle file in your project.
include :
Code:
'react-native-agconnect-remoteconfig'
Code:
project(':react-native-agconnect-remoteconfig').projectDir = new File(rootProject.projectDir,'../node_modules/@react-native-agconnect/remoteconfig/android')
Development Process
Open AGC, choose Growing > Remote Configuration, then click Enable now.
Now, we have to set the Parameters and Conditions.
-Parameter management is used to define key-value parameters. These parameters are used to configure the value in application.
-Condition management is used to define rules and if that rule criteria is met, value can be configured in the application. These rules are used based on App version, OS version, language, country, region etc.
1. Navigate to Growing > Remote Configuration and Click on Condition management tab and then click Add condition.
2. In the displayed dialog box, set Condition.
3. Click the Parameter management tab and then click Add parameter.
4. Enter a parameter name in Default parameter name based on your design. Enter a default value for the parameter in Default value.
5. After the parameters are added, click Release.
Code Implementation
Setting In-app Default Parameter Values
Call AGCRemoteConfig.applyDefault to set the default parameter values that will be displayed.
Code:
let map = new Map();
map.set("Know_more", ‘’);
AGCRemoteConfig.applyDefault(map);
Fetch the values from Cloud
Call AGCRemoteConfig.fetch(intervalSeconds) API to fetch the latest parameter values from the cloud and then call the AGCRemoteConfig.applyLastFetched API to make the values take effect.
Code:
AGCRemoteConfig.fetch(0)
.then(() => {
console.log("fetch result success");
AGCRemoteConfig.applyLastFetched();
})
Source of a Parameter Value
You can call AGCRemoteConfig.getSource to obtain the source of a parameter value to determine whether the parameter is a local one or is fetched.
Code:
AGCRemoteConfig.getSource("key").then((source) => {
//success
});
There are three types of source. STATIC, DEFAULT and REMOTE.
Get the Parameter values
After default parameter values are set or parameter values are fetched from cloud, you can call AGCRemoteConfig.getValue to obtain the parameter values through key values to use in your app.
Code:
AGCRemoteConfig.getValue("Know_more").then((data) => {
console.log("default_key_string ==" + (data));
});
Get all the Values
We can obtain all parameter values by calling getMergedAll API instead of key values. It will return all values obtained after the combination of the local values and values fetched from the cloud.
Code:
AGCRemoteConfig.getMergedAll().then((map) => {
map.forEach(function (value, key) {
console.log("key-->" + key + ",value-->" + value);
});
});
Resetting Parameter Values
We can clear all existing parameter values by calling clearAll API.
Code:
AGCRemoteConfig.clearAll();
For Example,
Code:
import * as React from 'react';
import { View, Button, StyleSheet } from 'react-native';
import AGCRemoteConfig, { SOURCE} from '@react-native-agconnect/remoteconfig';
const Separator = () => {
return <View style={styles.separator} />;
}
export default function ConfigScreen() {
return (
<View style={{ marginTop: 30, paddingHorizontal: 20 }}>
<Button
Title= “Know_more "
onPress={() => {
//add your code here
}}
/>
<Separator />
Testing
Enter the below command to run the project.
Code:
react-native run-android
Run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Output
You can check every change in your log
Tips and Tricks
1. Set minSdkVersion to 19 or higher.
2. The default update interval of the AGCRemoteConfig.fetch API is 12 hours. You can call the intervalSeconds API to customize the fetch interval. Calling fetch again within the interval does not trigger data synchronization from the cloud.
3. Once you have set the Parameters for remote configuration in AGC console, don’t forget to click on release.
Conclusion
In this article, we have learned how to integrate HMS Remote Configuration in React native. Remote Configuration is very useful for delivering the right user experience to users. Remote Configuration service can be used in your application as per your requirement.
Reference
Remote Configuration: Documentation
Remote Configuration: Training Video
Related
More articles like this, you can visit HUAWEI Developer Forum
In this article I’m going to show you how to integrate Cordova application with HMS bindings. But first let’s talk about what is Cordova and how to settings up an application using CLI.
What is Cordova?
Cordova is an open-source mobile development framework. It allows you to use standard web technologies such as HTML5, CSS3, and JavaScript for cross-platform development, avoiding each mobile platforms’ native development language. Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device’s sensors, data, and network status.
There are several components to a Cordova application. The following diagram shows a high-level view of the Cordova application architecture.
{
"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"
}
Use Cordova if you are:
a mobile developer and want to extend an application across more than one platform, without having to re-implement it with each platform’s language and tool set.
a web developer and want to deploy a web app that’s packaged for distribution in various app store portals.
a mobile developer interested in mixing native application components with a WebView (browser window) that can access device-level APIs, or if you want to develop a plugin interface between native and WebView components.
Setting Up Environments
Cordova command-line runs on Node.js and is available on NPM.
To ensure your machine has these environments;
Open a command prompt or Terminal, and type npm -v and node -v
I assume that, you’ve already installed these environments.
Open a command prompt or Terminal, and type npm install -g cordova
Once you finished installation, we’re ready to create cordova project.
Create a blank Cordova project using the command-line tool. Navigate to the directory where you wish to create your project and type cordova create <path> NAME_OF_APP.
For a complete set of options, type cordova help create.
After creating a Cordova project, navigate to the project directory. From the project directory, you need to add a platform for which you want to build your app.
To add android platform, type cordova platform add android.
Connect your phone to Machine and command line, run cordova run android. Application will be deploy on your phone.
Plugins.xml
Plugins are an integral part of the Cordova ecosystem. They provide an interface for Cordova and native components to communicate with each other and bindings to standard device APIs. This enables you to invoke native code from JavaScript.We will implement our plugin for execute scripts,
customized gradle file and modify manifest file.
Code:
<hook src="scripts/lib/moveAgconnectServices.js" type="before_plugin_install" />
<!-- hook for add maven repositories and agc plugin-->
<hook src="scripts/android/after_plugin_install.js" type="after_plugin_install" />
<hook src="scripts/android/before_plugin_uninstall.js" type="before_plugin_uninstall" />
<framework custom="true" src="src/android/build.gradle" type="gradleReference" />
<!-- Push Kit dependency-->
<framework src="com.huawei.hms:push:4.0.0.300" />
<framework src="com.huawei.agconnect:agconnect-core:1.3.1.300" />
<config-file target="res/xml/config.xml" parent="/*">
<feature name="PushPlugin">
<param name="android-package" value="com.hms.cordova.plugin.PushPlugin"/>
</feature>
</config-file>
<config-file parent="/manifest/application" target="AndroidManifest.xml">
<service android:exported="false" android:name="com.hms.cordova.plugin.PushService">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT" />
</intent-filter>
</service>
</config-file>
<source-file src="src/android/PushPlugin.java" target-dir="src/com/hms/cordova/plugin" />
<source-file src="src/android/PushService.java" target-dir="src/com/hms/cordova/plugin" />
Let’s focus on it step by step;
<hook src=”scripts/lib/moveAgconnectServices.js” type=”before_plugin_install” />
This hook parameter provide us to execute our custom script before plugin install. Therefore if we need to custom configuration, hook parameter provide us to handle it. As well as it provides after install, after uninstall and before uninstall.
<framework custom=”true” src=”src/android/build.gradle” type=”gradleReference” />
framework parameter identifies a framework (usually part of the OS/platform) on which the plugin depends. We’re using it for customized build.gradle file to add dependencies.
<config-file target=”res/xml/config.xml” parent=”/*”> <feature name=”PushPlugin”> <param name=”android-package” value=”com.hms.cordova.plugin.PushPlugin”/> </feature> </config-file>
config-file parameter identifies an XML-based configuration file to be modified. We’re using it for used to specify the push plugin. Also used for customized AndroidManifest.xml to add permissions.
<source-file src=”src/android/PushPlugin.java” target-dir=”src/com/hms/cordova/plugin” />
source-file parameter identifies executable source code that should be installed into a project. We’re using for our plugins which are PushPlugin and AnalyticsPlugin.
Writing Android Java Plugin
Writing a plugin requires an understanding of the architecture of Cordova-Android. Cordova-Android consists of an Android WebView with hooks attached to it. These plugins are represented as class mappings in the config.xml file.
A plugin will consist of at least a single Java class that extends the CordovaPlugin class. A plugin must override one of the execute methods from CordovaPlugin.
Code:
public class PushPlugin extends CordovaPlugin {
private static final String TAG = PushPlugin.class.getSimpleName();
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) {
if (action.equals("getToken")) {
getToken(callbackContext);
}
return true;
}
private void getToken(CallbackContext callbackContext) {
Log.i(TAG, "get token: begin");
try {
String appId = AGConnectServicesConfig.fromContext(cordova.getContext()).getString("client/app_id");
String pushToken = HmsInstanceId.getInstance(cordova.getContext()).getToken(appId, "HCM");
if (!TextUtils.isEmpty(pushToken)) {
Log.i(TAG, "******TOKEN******:" + pushToken);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, pushToken);
callbackContext.sendPluginResult(pluginResult);
}
} catch (Exception e) {
Log.e(TAG, "getToken Failed, " + e);
PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
callbackContext.sendPluginResult(pluginResult);
}
}
}
We compare the value of the action parameter, and dispatch the request off to a (private) method in the class, optionally passing some of the parameters to the method. We’re getting parameter from JavaScript’s exec function gets passed into the Plugin class's execute method than called getToken() metod.
Inside getToken() metod, we’re using HMS java code to provide us token depends on our appId, than we received token, return to callback with tokenId with PluginResult object. It will be pass data from java to JavaScript UI layer of our android application.
Code:
getToken: function() {
window.plugins.PushPlugin.getToken(function(res) {
alert( res);
}, function(err) {
alert(err);
});
},
In UI layer of android, we’re implement a button and add on_click trigger. As retun from PluginResult in CordovaActivity, show and alert of token which received from HmsInstanceId.
Can you please provide me with link to download cordova plugin in HMS ?
In my previous article, we learn how to integrate Huawei ML Kit Text-related service. Today we are going to explore language or voice-related service of machine learning kit.
Introduction
Huawei ML kit language-related service is used for detecting a text, convert a text to other language, reading a text etc. The scenario we can use this service is by creating an audio book like application which you can find in Huawei App Gallery.
Language/Voice-related Services
There are five type of services which comes under language-related service:
1) Text Translation
2) Language Detection
3) Text to Speech
4) Automatic Speech Recognition
5) Audio File Transcription
Here we will use three services that is Text Translation, Language Detection and Text to Speech to showcase the power HMS ML 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 and enable ML Kit in Manage Api section.
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) Download the Cordova Ml Kit Plugin. Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install <CORDOVA_MLKIT_PLUGIN_PATH>
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-ml" folder from library to "node_modules @iONiC-native" folder under your Ionic project.
Code:
cp node_modules/@hmscore/cordova-plugin-hms-ml/ionic/dist/hms-ml 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
Install FileChooser
We need to install FileChooser to select a file or in this case an image, returns a file URI. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-filechooser
npm install [user=1329689]@iONiC[/user]-native/file-chooser
ionic cap sync
Android Permission
We need android permission in order to allow our user to give their permission to the application like camera permission, storage permission etc. Run the following command on visual studio terminal:
Code:
npm install cordova-plugin-android-permissions
npm install [user=1329689]@iONiC[/user]-native/android-permissions
ionic cap sync
Avoid No Provider Error
To avoid No Provider Error, we need to add FileChooser, Android Permission and HMS ML kit in app.module.ts providers section and also make sure to import the same as shown below:
Code:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from [user=1329689]@iONiC[/user]/angular';
import { SplashScreen } from [user=1329689]@iONiC[/user]-native/splash-screen/ngx';
import { StatusBar } from [user=1329689]@iONiC[/user]-native/status-bar/ngx';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { AndroidPermissions } from [user=1329689]@iONiC[/user]-native/android-permissions/ngx';
import { FileChooser } from [user=1329689]@iONiC[/user]-native/file-chooser/ngx';
import { HMSMLKit } from [user=1329689]@iONiC[/user]-native/hms-ml/ngx'
import { FilePath } from [user=1329689]@iONiC[/user]-native/file-path/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
StatusBar,
SplashScreen,
AndroidPermissions,
FileChooser,
HMSMLKit,
FilePath,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Create page in Ionic
Run the following command to create page in Ionic project:
Code:
Ionic generate page page-name
Text Translation
Basically it helps us to translate text or multiple text into different language. Currently, the following languages are supported:
1) Simplified Chinese
2) English
3) French
4) Arabic
5) Thai
6) Spanish
7) Turkish
8) Portuguese
9) Japanese
10) German
11) Italian
12) Russian
This service will be very useful to tourists who wants to communicate with people who can’t speak their language. This service can run on both cloud and device.
Text translation service run on device:
Code:
async localTranslator() {
var localtranslateInput = {
targetLangCode: this.language,
sourceLangCode: "en",
sourceText: this.translateText,
apiKey:"YOUR_API_KEY"
};
try {
const result = await this.HmsMLKit.localTranslator(localtranslateInput);
this.translateResult = result;
} catch (ex) {
alert(ex)
}
}
Text translation service run on cloud:
Code:
async remoteTranslator() {
var remoteTranslateInput = {
targetLangCode: this.language,
sourceLangCode: "en",
sourceText: this.translateText,
apiKey:"YOUR_API_KEY"
};
try {
const result = await this.HmsMLKit.remoteTranslator(remoteTranslateInput);
this.translateResult = result;
} catch (ex) {
console.log(ex);
}
}
In both the cases do not forget to import HMSMLKit.
Overview
You can use App Messaging of AppGallery Connect to send relevant messages to target active users of your app to encourage them to use key app functions, or send attractive promotion activities to enhance user loyalty. App Messaging even allows you to customize your messages look and the way they will be sent, in addition to default message layouts. You can also define events for triggering message sending to your users at the right moment.
{
"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"
}
In this article, I will show how user can promote their products using InAppMesseage service.
App Messaging allows you to send targeted messages based on user behaviour in your app to engage users and encourage certain user activities such as update, browse, subscribe and purchase. For example, you can use this service to send a promotion message of a product. When a user views product information, improving the sales and purchase rate.
Create Project in Huawei Developer Console
Before you start developing an app, configure app information in App Gallery Connect.
Register as a Developer
Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, refer to Registration and Verification.
Create an App
Follow the instructions to create an app Creating an App Gallery Connect Project and Adding an App to the Project. Set the data storage location to Germany.
React Native setup
Requirements
Huawei phone with HMS 4.0.0.300 or later.
React Native environment with Android Studio, NodeJs and Visual Studio code.
Dependencies
Gradle Version: 6.3
Gradle Plugin Version: 3.5.2
React Native CLI: 2.0.1
1. Environment set up, refer link.
2. Create project using below command.
Code:
react-native init project name
3. 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
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, navigate to JDK directory’s bin folder and open a terminal in this directory. Execute the following command:
Code:
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
This command creates the keystore file in application_project_dir/android/app
The next step is to obtain the SHA256 key which is needed for authenticating your app to Huawei services, for the key store file. To obtain it, enter following command in terminal:
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
After an authentication, the SHA256 key will be revealed as shown below.
Adding SHA256 Key to the Huawei project in App Gallery.
Copy the SHA256 key and visit AppGalleryConnect/ <your_AppMessage_project>/General Information. Paste it to the field SHA-256 certificate fingerprint.
Download the agconnect-services.json from App Gallery and place the file in android/app directory from your React Native Project.
Follow the steps to integrate the InAppMessage plugin to your React Native Application.
Enable the AppMessaging and Analytics kit from ManageAPIs as below.
Integrate the Hms-InAppMessage plugin:
User have react native version 16.6.0 install below command
Code:
npm install @react-native-agconnect/[email protected]
User have react native version 17.0.0 install below command
Code:
npm install --legacy-peer-deps @react-native-agconnect/appmessaging
Download the Plugin from the Download Link
Download ReactNative InAppMessage Plugin under node_modules/@react-native-agconnect of your React Native project, as shown in the directory tree below:
Code:
project-dir
|_ node_modules
|_ ...
|_ @react-native-agconnect
|_ ...
|_ appmessaging
|_ ...
|_ ...
Navigate to android/app/build.gradle directory in your React Native project. Follow the steps:
Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
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.4.1.300’)
Android setup:
Step 1: An example of your AndroidManifest.xml as follows:
Code:
<activity
android:name="com.huawei.agc.rn.appmessaging.example.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Step 2: Open the build.gradle file in the android directory of your React Native project, and change the value of minSdkVersion in buildscript to 19.
Code:
defaultConfig {
applicationId "<package_name>"
minSdkVersion 19
/*
* <Other configurations>
*/
}
Creating an In-App MessageTo send huawei in-app messages to users in specific scenarios, you need to create them in AppGallery Connect first and set the message layout and sending target
Procedure1. Sign in to AppGallery Connect and click My projects.
2. Find and click your project.
3. Navigate to Grow > App Messaging and click New.
4. Set Name and Description
5. Set the layout and content and click Next.
Select the message type from the Type drop-down list box. Currently, the following options are supported: Pop-up, Image, and Banner.
6. Set the sending time and click Next.
7. Set conversion events.
Associate the display or tap of the in-app message with a conversion event. The conversion relationship will be displayed in statistics.
8. Click Save and Publish in the upper right corner to complete message creation.
In-App Message DisplayThe prerequisites for the React Native App Messaging plug-in to display in-app messages as follows:
1. The app must be running on the foreground.
2. A user triggers the event upon which an in-app message will be displayed. Then the React Native App Messaging plug-in synchronizes the message data from the AppGallery Connect server or obtains the message data from the local cache and determines whether to display the message.
Add Below Code in App.js:
The AGCAppMessaging.setFetchMessageEnable API can be called to enable or disable data synchronization from the AppGallery Connect server.
Code:
setFetchMessageEnable() {
AGCAppMessaging.getInstance().setFetchMessageEnable(true).then(result => {
Alert.alert("[setFetchMessageEnable] " + JSON.stringify(result));
this.createCustomView("setFetchMessageEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setFetchMessageEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setFetchMessageEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
The AGCAppMessaging.setDisplayEnable API can be called to set whether to enable message display.
Code:
setDisplayEnable() {
AGCAppMessaging.getInstance().setDisplayEnable(false).then(result => {
Alert.alert("[setDisplayEnable] " + JSON.stringify(result));
this.createCustomView("setDisplayEnable : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[setDisplayEnable] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[setDisplayEnable] Error/Exception: ", JSON.stringify(err) + "")
});
}
To add a custom view on the Android platform, add the following code to the onCreate method of your React-Native project /Android/MainApplication.java.
Code:
AgcAppMessagingModule.addCustomView();
Call the AGCAppMessaging.handleCustomViewMessageEvent for custom app message interactions. The following example calls the AGCAppMessaging.ON_MESSAGE_DISPLAY event once the custom app message has been shown:
Code:
componentDidMount() {
this.addMessageCustomViewListener();
}
addMessageCustomViewListener = () => {
AGCAppMessaging.getInstance().addMessageCustomViewListener((result) => {
Alert.alert(AGCAppMessaging.EventTypes.CUSTOM_VIEW + JSON.stringify(result))
/*
* Add Custom Message Event Handler method.
* When using custom app message layout, handle custom app message click events like below.
* gets eventType ( AGCAppMessaging.ON_MESSAGE_DISPLAY, AGCAppMessaging.ON_MESSAGE_CLICK, AGCAppMessaging.ON_MESSAGE_DISMISS, AGCAppMessaging.ON_MESSAGE_ERROR)
* and dismissType param( AGCAppMessaging.DISMISS_TYPE_CLICK, AGCAppMessaging.DISMISS_TYPE_CLICK_OUTSIDE, AGCAppMessaging.DISMISS_TYPE_AUTO, AGCAppMessaging.DISMISS_TYPE_SWIPE) when using AGCAppMessaging.ON_MESSAGE_DISMISS.
*/
this.handleCustomViewMessageEvent();
});
handleCustomViewMessageEvent() {
const customMessageDisplayReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISPLAY
}
const customMessageClickReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_CLICK
}
const customMessageDismissReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_DISMISS,
"dismissType": AGCAppMessaging.DismissTypes.DISMISS_TYPE_CLICK
}
const customMessageErrorReq = {
"eventType" : AGCAppMessaging.EventTypes.ON_MESSAGE_ERROR
}
AGCAppMessaging.getInstance().handleCustomViewMessageEvent(customMessageDisplayReq).then(result => {
Alert.alert("[handleCustomViewMessageEvent] " + JSON.stringify(result));
this.createCustomView("handleCustomViewMessageEvent : ", JSON.stringify(result) + "")
}).catch((err) => {
Alert.alert("[handleCustomViewMessageEvent] Error/Exception: " + JSON.stringify(err));
this.createCustomView("[handleCustomViewMessageEvent] Error/Exception: ", JSON.stringify(err) + "")
});
}
class AGCAppMessaging{
constructor() {
this.emitter = new NativeEventEmitter(AGCAppMessagingModule);
}
static getInstance() {
if (!this.instance) {
this.instance = new AGCAppMessaging();
}
return this.instance;
}
addMessageDisplayListener(listener){
return subscription = this.emitter.addListener(
EventTypes.ON_MESSAGE_DISPLAY, listener
);
}
Test InAppMessage
Huawei In-app messages can only be displayed to users who have installed your officially released app. App Messaging allows you to test an in-app message when your app is still under tests. The testing procedure is as follows:
1. Obtain the anonymous application identifier (AAID) of the test device. For details, refer to Obtaining AAID.
2. Sign in to AppGallery Connect and select My projects.
3. Find your project from the project list and click the app for which you want to test an in-app message on the project card.
4. Navigate to Growing > App Messaging > Management, find the message that you need to test, and click Test in the Operation column.
5. Click Add test user and enter the AAID of the test device in the text box.
6. Click Save to set the in-app message to a test message and save the device as a test device.
Run the application (Generating the Signed Apk):
1. Open project directory path in command prompt.
2. Navigate to android directory and run the below command for signing the Apk.
Code:
gradlew assembleRelease
Output:
Tips and Tricks
Download latest HMS ReactNativeAppMessage plugin.
Add AAID to Test AppMessage in AppGalleryConnect.
For project cleaning, navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion:
In this article, we have learnt to integrate InAppMessage in React native project. We can integrate this service in different scenarios such as Travel, Education, Finance, Gaming and E-commerce apps to send the update, browse, subscribe and promote the product for better sales.
Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment below.
Reference:
App Messaging
Original Source
{
"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
{
"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