HMS AGC CloudStorage Kit Integration in B4A Platform - Huawei Developers

Overview
Cloud Storage Service allows you to store high volumes of data such as images, audios, and videos generated by your users securely and economically with direct device access. The service is stable, secure, efficient, and easy-to-use, and can free you from development, deployment, O&M, and capacity expansion of storage servers.
In this article, let us learn how to do the following:
Create an app and configure its information in AppGallery Connect.
Use B4A IDE to integrate the HUAWEI HMS Cloud Storage SDK into your app and develop storage-related functions.
Build and demonstrate a demo app.
Manage files on the Cloud Storage page in AppGallery Connect.
For details on installation and configuration of B4A IDE, please refer to https://www.b4x.com/b4a.html
Creating Wrapper Class
1. Download the following AAR package inside Addition folder in your project directory
HMSSDK AGConnect:
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-auth/1.4.1.300/agconnect-auth-1.4.1.300.aar
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-core/1.4.0.300/agconnect-core-1.4.0.300.aar
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-storage/1.3.0.300/agconnect-storage-1.3.0.300.aar
https://developer.huawei.com/repo/com/huawei/agconnect/datastore-core/1.4.1.300/datastore-core-1.4.1.300.aar
https://developer.huawei.com/repo/com/huawei/agconnect/datastore-annotation/1.4.1.300/datastore-annotation-1.4.1.300.jar
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-https/1.4.1.300/agconnect-https-1.4.1.300.aar
https://developer.huawei.com/repo/com/huawei/agconnect/agconnect-credential/1.4.1.300/agconnect-credential-1.4.1.300.aar
HMSSDK Base:
https://developer.huawei.com/repo/com/huawei/hms/base/5.0.0.301/base-5.0.0.301.aar
HMSSDK Update:
https://developer.huawei.com/repo/com/huawei/hms/availableupdate/5.0.0.301/availableupdate-5.0.0.301.aar
https://developer.huawei.com/repo/com/huawei/hms/update/2.0.6.302/update-2.0.6.302.aar
HMSSDK Device:
https://developer.huawei.com/repo/com/huawei/hms/device/5.0.0.301/device-5.0.0.301.aar
HMSSDK DynamicAPI:
https://developer.huawei.com/repo/com/huawei/hms/dynamic-api/1.0.13.303/dynamic-api-1.0.13.303.aar
HMSSDK Log:
https://developer.huawei.com/repo/com/huawei/hms/log/5.0.0.301/log-5.0.0.301.aar
HMSSDK Network:
https://developer.huawei.com/repo/com/huawei/hms/network-common/4.0.2.300/network-common-4.0.2.300.aar
https://developer.huawei.com/repo/com/huawei/hms/network-grs/4.0.2.300/network-grs-4.0.2.300.aar
HMSSDK Stats:
https://developer.huawei.com/repo/com/huawei/hms/stats/5.0.0.301/stats-5.0.0.301.aar
HMSSDK Tasks:
https://developer.huawei.com/repo/com/huawei/hmf/tasks/1.4.1.300/tasks-1.4.1.300.aar
HMSSDK UI:
https://developer.huawei.com/repo/com/huawei/hms/ui/5.0.0.301/ui-5.0.0.301.aar
Squareup Libraries:
https://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.11.0/okhttp-3.11.0.jar
https://repo1.maven.org/maven2/com/squareup/okio/okio/1.14.0/okio-1.14.0.jar
Note: After download of the above AAR files, create Addition folder inside Project and keep all AAR packages in it.
2. Open each of the AAR package with RAR tool and rename the class.jar and AndroidManifest.xml files. And save those jar files inside libs folder (It is recommended that the two files be renamed consistently with the AAR package names.)
{
"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"
}
3. Copy required permissions in the <manifest> section in B4A IDE. Remember to aggregate all the permissions as shown below.
4. Copy all configurations, referring to the AndroidManifest.xml file in all AAR files, to the <application> section in the B4A IDE Manifest Editor.
NOTE: Remember to aggregate all the configurations in relevant sections as shown below.
5. Change all occurrences of ${applicationId} to $PACKAGE$.
6. Download the configuration file (agconnect-services.json) from App Gallery Connect and add the JSON File to the assets Folder.
B4A will automatically incorporate files in the assets folder of an AAR package to the assets folder of your main project.
Encapsulating Java Files Using SLC
Create Library as parent and then create bin, libs and src as subfolder in the project directory
2. Develop java project inside the following path,
Library Folder > src > b4x > hms > cloudstorage
a. Import the following two lines of code to each Java file
Code:
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.*;
b. Add necessary annotations to the Java files
[CODE @version(1.0f)
@ShortName("CloudStorageFuncs")
@DependsOn(values={
"agconnect-auth-1.4.1.300.aar",
"agconnect-core-1.4.0.300.aar",
"agconnect-storage-1.3.0.300.aar",
"availableupdate-5.0.0.301.aar",
"base-5.0.0.301.aar",
"device-5.0.0.301.aar",
"dynamic-api-1.0.13.303.aar",
"log-5.0.0.301.aar",
"network-common-4.0.2.300.aar",
"network-grs-4.0.2.300.aar",
"stats-5.0.0.301.aar",
"tasks-1.4.1.300.aar",
"ui-5.0.0.301.aar",
"update-2.0.6.302.aar",
"okhttp-3.11.0.jar",
"datastore-core-1.4.1.300.aar",
"datastore-annotation-1.4.1.300.jar",
"agconnect-https-1.4.1.300.aar",
"agconnect-credential-1.4.1.300.aar",
"okio-1.14.0.jar"
})
[/CODE]
c. Modify the context.
B4A does not recognize the Context class. Therefore, when parsing a class that contains the @version(1.0f) annotation, it will report an error if a method of the class has referenced Context. In this case, you need to change Context to the B4A object BA.
Code:
public void init(BA ba) {
Log.d(LOGTAG, "init entered. before AGConnectInstance initialize() ");
Log.d(LOGTAG, "init before AGCStorageManagement.getInstance()");
mAGCStorageManagement = AGCStorageManagement.getInstance();
if(mAGCStorageManagement == null){
Log.d(LOGTAG, "init entered. before AGConnectInstance initialize() ");
showToast(ba, "mAGCStorageManagement == null");
AGConnectInstance.initialize(ba.context);
Generating library
1. Download SimpleLibraryCompiler from the below link,
www.b4x.com/android/files/SimpleLibraryCompiler.zip
2. Go to Project > Build Configurations and change the B4A project package name to the project package name configured in App Gallery Connect
3. Select the Addition folder and add AAR packages to it.
4. Select the project folder, define the library name, and click Compile
Integrating the HMS Cloud Storage Kit Libraries for B4A
Enable library in B4A IDE
Add the #AdditionalJar field to Project Attributes to reference the AAR packages
Code:
#Region Module Attributes
#FullScreen: False
#IncludeTitle: True
#ApplicationLabel: HMSCloudStorageCodelabs
#VersionCode: 1
#VersionName:
#SupportedOrientations: unspecified
#CanInstallToExternalStorage: False
#AdditionalJar: agconnect-auth-1.4.1.300.aar
#AdditionalJar: agconnect-core-1.4.0.300.aar
#AdditionalJar: agconnect-storage-1.3.0.300.aar
#AdditionalJar: availableupdate-5.0.0.301.aar
#AdditionalJar: base-5.0.0.301.aar
#AdditionalJar: device-5.0.0.301.aar
#AdditionalJar: dynamic-api-1.0.13.303.aar
#AdditionalJar: log-5.0.0.301.aar
#AdditionalJar: network-common-4.0.2.300.aar
#AdditionalJar: network-grs-4.0.2.300.aar
#AdditionalJar: stats-5.0.0.301.aar
#AdditionalJar: tasks-1.4.1.300.aar
#AdditionalJar: ui-5.0.0.301.aar
#AdditionalJar: update-2.0.6.302.aar
#AdditionalJar: okhttp-3.11.0.jar
#AdditionalJar: datastore-core-1.4.1.300.aar
#AdditionalJar: datastore-annotation-1.4.1.300.jar
#AdditionalJar: agconnect-https-1.4.1.300.aar
#AdditionalJar: agconnect-credential-1.4.1.300.aar
#AdditionalJar: okio-1.14.0.jar
#End Region
Add below code in B4A project to call the methods written for cloud storage kit.
Code:
Sub Process_Globals
Private rp As RuntimePermissions
End Sub
Sub Globals
Dim locationPermissionGranted As Int
Dim CSFuncs As CloudStorageFuncs
End Sub
Sub Activity_Create(FirstTime As Boolean)
Activity.LoadLayout("AccountAuthCS")
Log("Entered Activity_Create")
'Following Runtime Dangerous Permissions needed for accessing Cloud Storage SDK
rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
rp.CheckAndRequest(rp.PERMISSION_READ_EXTERNAL_STORAGE)
Log("Activity_PermissionResult before init")
CSFuncs.init
Log("Activity_PermissionResult before showToast")
CSFuncs.showToast("CSFuncs init completed")
Log("Activity_Create exit ")
End Sub
' Callback on permission granted / denied by the user.
Sub Activity_PermissionResult (Permission As String, Result As Boolean)
Log("Activity_PermissionResult entered")
If Permission = rp.PERMISSION_WRITE_EXTERNAL_STORAGE Then
If True = Result Then
locationPermissionGranted = locationPermissionGranted + 1
Log("Activity_PermissionResult rp.PERMISSION_WRITE_EXTERNAL_STORAGE Result = " & Result)
End If
End If
If Permission = rp.PERMISSION_READ_EXTERNAL_STORAGE Then
If True = Result Then
locationPermissionGranted = locationPermissionGranted + 1
Log("Activity_PermissionResult rp.PERMISSION_READ_EXTERNAL_STORAGE Result = " & Result)
End If
End If
If 2 = locationPermissionGranted Then
Log("Activity_PermissionResult, permission granted")
End If
End Sub
Sub Activity_Start
Log("Activity_Start entered")
End Sub
Sub Activity_Resume
Log("Activity_Resume entered")
End Sub
Sub Activity_Pause (UserClosed As Boolean)
Log("Activity_Pause entered")
End Sub
Sub Activity_Stop
Log("Activity_Stop entered")
End Sub
Sub Button3_Click
Log("Button3_Click entered")
Log("Button3_Click before uploadFile")
CSFuncs.uploadFile("sample_file.txt")
End Sub
Sub Button2_Click
Log("Button2_Click entered")
Log("Button2_Click before Auth login")
CSFuncs.login
End Sub
Sub Button7_Click
Log("Button7_Click entered")
Log("Button7_Click before deleteFile")
CSFuncs.deleteFile("sample_file.txt")
End Sub
Sub Button6_Click
Log("Button6_Click entered")
Log("Button6_Click before updateFileMetadata")
CSFuncs.updateFileMetadata("sample_file.txt")
End Sub
Sub Button5_Click
Log("Button5_Click entered")
Log("Button5_Click before getFileMetadata")
CSFuncs.getFileMetadata("sample_file.txt")
End Sub
Sub Button4_Click
Log("Button4_Click entered")
Log("Button4_Click before getFileList")
CSFuncs.getFileList("/")
End Sub
Sub Button1_Click
Log("Button1_Click entered")
Log("Button1_Click before downloadFile")
CSFuncs.downloadFile("sample_file.txt")
End Sub
Integrating the HMS Core SDK
Before you start developing an app, integrate the HMS Core SDK into your project.
a. Sign in to AppGallery Connect and select My Projects.
b. Find your app from the list and click the app name.
c. Enable Cloud Storage Kit in App gallery connect
d. Go to Develop > Overview > App information.
e. Click agconnect-services.json to download the configuration file.
Configuring App Information
In order to enable the communication between your application and the AppGallery, there are some configurations that need to be made.
Configuring the Signing Certificate
1. Sign in to AppGallery Connect and select My Projects.
2. Find your app from the list and click the app name.
3. In the App information section of the page, set SHA-256 certificate fingerprint to the SHA-256 fingerprint that was generated in the preceding Obtaining the SHA-256 Fingerprint From Signature File section.
Setting Package Signing Options
To create a signed application package perform the following steps:
1. Go to Tools > Private Sign Key and select the SHA256 signature file specified in AppGallery Connect as the B4A project signature file.
2. Declare MainApplication in the Manifest file.
The path of MainApplication must also be the path to the src folder where MainApplication is located.
Testing the App
Open the developed app and check whether it can execute all the cloud storage methods properly.
Verify on the AGC console that the cloud storage methods have executed properly.
Congratulations
Well done. You have successfully learned how to:
Create an app and configure its information in AppGallery Connect.
Use B4A IDE to integrate the HUAWEI HMS Cloud Storage SDK into your app and develop storage-related functions.
Build and demonstrate a demo app.
Manage files on the Cloud Storage page in AppGallery Connect

Related

How to Integrate HUAWEI Analytics Kit in Cordova

Hello everyone, in this article, provides example of HUAWEI Analytics Kit using the Cordova mobile application. But first, let me inform you about HUAWEI Analytics Kit a little.
About HUAWEI Analytics Kit
Offers a rich array of preset analytics models that help you gain a deeper insight into your users, products, and content.
Helps you gain insight into how your users behave on different platforms based on the user behavior events and user attributes reported by your app.
Diverse analytics models: analyzes events, behavior, audiences, funnels, retention, attribution, real-time data.
App Debugging: During app development, the product manager and technical team can cooperate with each other through app debugging to verify data reporting, preventing missing events and event attribute errors.
There are 3 types of events: automatically collected, predefined and custom.
With these insights, you can then take a data-driven approach to make informed decisions for product and marketing optimizations.
Privacy Statement: HUAWEI Analytics Kit does not collect users’ personal data. If your app needs to collect user data, it must do so in accordance with all applicable laws and regulations. You’ll also need to display a privacy statement, so users understand how you’re planning to use their data.
Integrating the AppGallery Connect SDK
Integrating AppGallery Connect is a prerequisite for using HUAWEI Analytics Kit is offering in your application. If you want to use the AppGallery Connect Analytics service, you must first have a AppGallery Connect developer account and integrate HMS Core in your application. You need to create an project from your developer account and then integrate the Cordova HMS Analytics Plugin into your project.
Creating an AppGallery Connect Project
Sign in to AppGallery Connect and select My projects.
Click Add 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"
}
Enter a project name and click OK.
After the project is created, the Project settings page is displayed. You need to add an app to the project.
Adding an App to the Project
Before you use development capabilities provided by AppGallery Connect, you need to add an app to your project first.
Sign in to AppGallery Connect and select My projects.
Click your project from the project list.
Go to Project settings > General information, and click Add app.
On the Add app page, enter app information.
On the Project settings page, enter SHA-256 certificate fingerpring and then download the configuration file agconnect-services.json for Android platform.
Generating a Signing SHA-256 Certificate Fingerprint
On the Project settings page, download the configuration file agconnect-services.plist for iOS platform.
App Information - iOS Platform
Please refer to Configuring App Information in AppGallery Connect and Enabling Huawei Analytics
Integrating the HMS Analytics Plugin
You can either install the plugin through npm or by downloading it from the download page, Cordova Analytics plugin.
Download Cordova Analytics Sample Project Code
Run the following command in the project root directory of your Cordova project to install it through npm.
Code:
cordova plugin add @hmscore/cordova-plugin-hms-analytics
# install the plugin manually after downloading plugin
cordova plugin add <CORDOVA_ANALYTICS_PLUGIN_PATH>
Add the Android platform to the Cordova project
Please refer to Android App Development
Add the iOS platform to the Cordova project
Please refer to iOS App Development
Using Debug Mode
During the development, you can enable the debug mode to view the event records in real time, observe the results, and adjust the event reporting policies.
Enabled Debug Mode and after then the data is successfully reported, you can go to HUAWEI Analytics > App debugging to view the reported data, as shown in the following figure.
Android Platform
Run the following command to enable the debug mode:
Code:
adb shell setprop debug.huawei.hms.analytics.app package_name
Run the following command to disable the debug mode:
iOS Platform
During the development, you can use DebugView to view the event records in real time, observe the results, and adjust the event reporting policies.
To enable the debug mode: Choose Product > Scheme > Edit Scheme from the Xcode menu. On the Arguments page, click + to add the -HADebugEnabled parameter. After the parameter is added, click Close to save the setting.
To disable the debug mode
Viewing Debugging Event Details (Real-time Update)
Sign in to AppGallery Connect and click My projects.
Find your project, and click the app for which you want to view analytics data.
Go to HUAWEI Analytics > App debugging.
The App debugging page displays events reported by the app in the last 60 seconds or last 30 minutes.
If you select Last 60 seconds, the displayed page is as follows.
If you select Last 30 minutes, the displayed page is as follows.
What is AAID(Anonymous Application ID)?
Anonymous device ID opened to third-party apps. Each app is allocated with a unique AAID on the same device so that statistics can be collected and analyzed for different apps (for example, statistics on the number of active users). In addition, personal data from different apps is isolated to protect user data privacy and security.
Code:
/**
* Obtains the app instance ID from AppGallery Connect.
*/
async function onGetAAID() {
try {
const aaid = await HMSAnalytics.getAAID();
alert('getAAID -> Success -> aaid : ' + aaid);
} catch (err) {
alert('getAAID -> Error : ' + err);
}
}
How to records event?
Records custom event
Such events can be used to meet personalized analysis requirements that cannot be met by automatically collected events and predefined events.
Note: The ID of a custom event cannot be the same as that of a predefined event. Otherwise, the custom event will be identified as a predefined event.
Code:
/**
* Report custom events.
*/
async function onEvent() {
const name = 'event_name';
const value = {
"my_event_key": "my_event_value",
"my_event_key_two": "my_event_value_two"
};
try {
const event = await HMSAnalytics.onEvent(name, value);
alert('onEvent -> Success');
} catch (err) {
alert('onEvent -> Error : ' + err);
}
}
Records predefined event
Such events have been predefined by the HMS Core Analytics SDK based on common application scenarios. It is recommended you use predefined event IDs for event collection and analysis.
Code:
/**
* Report predefined events.
*/
async function onSendPredefinedEvent() {
const event_name = HMSAnalytics.HAEventType.SUBMITSCORE;
const event_value = {}
event_value[HMSAnalytics.HAParamType.SCORE] = 12;
event_value[HMSAnalytics.HAParamType.CATEGORY] = "SPORT";
try {
const event = await HMSAnalytics.onEvent(event_name, event_value);
alert('sendPredefinedEvent -> Success');
} catch (err) {
alert('sendPredefinedEvent -> Error : ' + err);
}
}
Please refer to Event Management
Setting User Profiles
Sets user attributes. The values of user attributes remain unchanged throughout the app lifecycle and during each session.
Note: A maximum of 25 user attributes are supported. If the name of an attribute set later is the same as that of an existing attribute, the value of the existing attribute is updated.
Code:
async function onSetUserProfile() {
const userProfileName = "user_profile_name";
const userProfileValue = "user_profile_value";
try {
const setUserProfile = await HMSAnalytics.setUserProfile(userProfileName, userProfileValue);
alert('setUserProfile -> Success');
} catch (err) {
alert('setUserProfile -> Error : ' + err);
}
}
When is the clearCacheData() method used?
It is used when deletes all collected data cached locally, including cached data that failed to be sent.
Note: AAID will be reset. Custom user attributes will be delete.
Code:
async function onClearCachedData() {
try {
const clearCachedData = await HMSAnalytics.clearCachedData();
alert('clearCachedData -> Success');
} catch (err) {
alert('clearCachedData -> Error : ' + err);
}
}
How to define a custom page?
Customizes a page entry event. The API applies only to non-activity pages because automatic collection is supported for activity pages.
Note: If this API is called for an activity page, statistics on page entry and exit events will be inaccurate.
Defines a custom page
After this pageStart() method is called, the pageEnd() API must be called.
Code:
/**
* Defines a custom page entry event.
* @note This method is only to support on Android Platform.
*/
async function onPageStart() {
const start_page_name = "start_page_name";
const start_page_class_override = "start_page_class_override";
try {
const pageStart = await HMSAnalytics.pageStart(start_page_name, start_page_class_override);
alert('pageStart -> Success');
} catch (err) {
alert('pageStart -> Error : ' + err);
}
}
Before this pageEnd() method is called, the pageStart() API must be called.
Code:
/**
* Defines a custom page exit event.
* @note This method is only to support on Android Platform.
*/
async function onPageEnd() {
const end_page_name = "start_page_name";
try {
const pageEnd = await HMSAnalytics.pageEnd(end_page_name)
alert('pageEnd -> Success' + pageEnd);
} catch (err) {
alert('pageEnd -> Error : ' + err);
}
}
Conclusion
In this article you have learned how to integrate HMS Analytics to your Cordova projects, record custom events and monitor them in AppGallery Connect. You can use custom events with user attributes in your apps to see user behaviors, so that you can improve your app depend on them.
Thank you!
Other Huawei Developers Cordova Medium Publications
References
Stack Overflow is the best place for any programming questions. Be sure to tag your question with huawei-mobile-services.
GitHub is the official repository for these plugins, You can open an issue or submit your ideas.
Huawei Developer Forum HMS Core Module is great for general questions, or seeking recommendations and opinions.
Huawei Developer Docs is place to official documentation for all HMS Core Kits, you can find detailed documentations in there.
If you run into a bug in our samples, please submit an issue to the GitHub repository.
Do we need to add huawei analytics dependencies in app-level build.gradle or HMS_analytics plugin will have the dependencies?

Intermediate - How to Integrate HMS Kits into Hotel booking application (Analytics & Site Kit)

Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article, I have implemented Analytics kit and Site Kit.
{
"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"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Analytics and Site Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
XML:
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...
</manifest>
3. Refer below URL for cross-platform plugins. Download required plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001051088628-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: hotelbooking
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_ads:
path: ../huawei_ads/
huawei_account:
path: ../huawei_account/
huawei_site:
path: ../huawei_site/
huawei_analytics:
path: ../huawei_analytics/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Analytics kit
Account kit is valuable in terms of analysis and reporting that we use frequently in our application. Using analytics we can check user behavior custom events and predefined events.
Service Features
By integrating the HMS Core Analytics SDK, you can:
1. Collect and report custom events through coding.
2. Set a maximum of 25 user attributes.
3. Automate event collection and session calculation with predefined event IDs and parameters.
HUAWEI Analytics Kit identifies users and collects statistics on users by an anonymous application identifier (AAID). The AAID is reset in the following scenarios:
1. Uninstall or reinstall the app.
2. The user clears the app data.
After the AAID is reset, the user will be counted as a new user.
There are 3 types of events:
Automatically collected
Predefined
Custom
Automatically collected events are collected from the moment you enable the kit in your code. Event IDs are already reserved by HUAWEI Analytics Kit and cannot be reused.
Predefined events include their own Event IDs which are predefined by the HMS Core Analytics SDK based on common application scenarios. The ID of a custom event cannot be the same as a predefined event’s ID. If so, you will create a predefined event instead of a custom event.
Custom events are the events that you can create for your own requirements.
Integration
What is AAID?
Anonymous device ID opened to third-party apps. Each app is allocated with a unique AAID on the same device, so that statistics can be collected and analyzed for different apps.
Code:
void getAAID() async{
String aaid = await mAnalytics.getAAID();
print(aaid);
}
Custom Events
Such events can be used to meet personalized analysis requirements that cannot be met by automatically collected events and predefined events.
Note: The ID of a custom event cannot be the same as that of a predefined event. Otherwise, the custom event will be identified as a predefined event
Adding Custom Events
In AppGallery Connect from left side panel open Huawei Analytics > Management > Events
Code:
void customEvent() async {
String name = "Custom";
dynamic value = {'customEvent': "custom Event posted"};
await _hmsAnalytics.onEvent(name, value);
}
Predefined Events
Such events have been predefined by the HMS Core Analytics SDK based on common application scenarios. It is recommended you use predefined event IDs for event collection and analysis.
Code:
void logEvent() async{
String name = HAEventType.SUBMITSCORE;
dynamic value = {HAParamType.SCORE: 15};
await mAnalytics.onEvent(name, value);
}
Site kit
This kit basically provide users with easy and reliable access to related locations and places. With the HMS Site kit we can provide them below features.
1. We can take place suggestions according to the keywords that we have determined.
2. According to the location of the user’s device, we can search for nearby places.
3. We can get detailed information about a location.
4. We can learn the human readable address information of a coordinate point.
5. We can learn the time period where a coordinate point is found.
HMS Site kit – Nearby Search
We can search for many places such as tourist attractions, restaurants, schools and hotels by entering information such as keywords, coordinates. Using this kit we can restrict to specific types using poiType, we can easily access many different information about places such as name, address, coordinates, phone numbers, pictures, address details. Within the Address Detail 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.
We need to create a NearbySearchRequest object to perform searching by keyword. We will perform the related search criteria on this NearbySearchRequest object.
While performing this operation, we need set many different criteria as we see in the code snippet. Let us examine the duties of these criteria one by one
1. Query: Used to specify the keyword that we will use during the search process.
2. 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.
3. 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.
4. CountryCode: It is using to limit search results according to certain country borders.
5. 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.
6. PageSize: Results return with the Pagination structure. This parameter is used to determine the number of Sites to be found in each page.
7. PageIndex: It is used to specify the number of the page to be returned with the Pagination structure.
Code:
void loadNearBy(String value) async {
SearchService service = new SearchService();
NearbySearchRequest searchRequest = NearbySearchRequest();
searchRequest.language = "en";
searchRequest.query = value;
searchRequest.poiType = LocationType.RESTAURANT;
searchRequest.location = Coordinate(lat: 12.976507, lng: 77.7356);
searchRequest.pageIndex = 1;
searchRequest.pageSize = 15;
searchRequest.radius = 5000;
NearbySearchResponse response = await service.nearbySearch(searchRequest);
if (response != null) {
setState(() {
mSitesList = response.sites;
});
}
}
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. Enable Auto refresh in AppGallery connect it will automatically update events in console
3. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Analytics kit and Site kit in this article. We have learned how to record events and monitor them in AppGallery Connect and also we have learned how to integrated site kit and how nearby search will work.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Analytics Kit URL
Site Kit URL
Read full article.

Beginner: Integration of Huawei InAppMessage feature for promoting products in E-commerce app (React Native)

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 Message​To 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
Procedure​1. 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 Display​The 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

Learn how to Integrate Huawei Remote Configuration services 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, 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

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