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

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.

Related

How to Integrate HUAWEI Analytics Kit in Cordova

Hello everyone, in this article, provides example of HUAWEI Analytics Kit("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050134725") using the Cordova mobile application. But first, let me inform you about HUAWEI Analytics Kit a little.
{
"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"
}
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("https://developer.huawei.com/consumer/en/service/josp/agc/index.html") 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
1. Sign in to AppGallery Connect and select My projects.
2. Click Add project.
3. Enter a project name and click OK.
4. 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.
1. Sign in to AppGallery Connect and select My projects.
2. Click your project from the project list.
3. Go to Project settings > General information, and click Add app.
4. On the Add app page, enter app information.
5. 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("https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/game-preparation-v4#certificate")
6. On the Project settings page, download the configuration file agconnect-services.plist for iOS platform.
Please refer to Configuring App Information in AppGallery Connect and Enabling Huawei Analytics("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/config-agc-0000001050134733")
Integrating the HMS Analytics Plugin
You can either install the plugin through npm or by downloading it from the download page, Cordova Analytics plugin("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Library-V1/cordova-sdk-download-0000001050134773-V1").
Download Cordova Analytics Sample Project Code("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Examples/cordova-sample-code-0000001051065444")
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("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/integrating-analytics-plugin-0000001059115018#EN-US_TOPIC_0000001059115018__section1258032454214")
Add the iOS platform to the Cordova project
Please refer to iOS App Development("https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/integrating-analytics-plugin-0000001059115018#EN-US_TOPIC_0000001059115018__section55836242421")
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:
Code:
adb shell setprop debug.huawei.hms.analytics.app .none.
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("https://developer.huawei.com/consumer/en/service/josp/agc/index.html") 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("https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/meta-manage-0000001050985177-V5#EN-US_TOPIC_0000001058394233__section6951855205619")
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("https://medium.com/huawei-developers/tagged/cordova")
References
Stack Overflow("https://stackoverflow.com/questions/tagged/huawei-mobile-services") is the best place for any programming questions. Be sure to tag your question with huawei-mobile-services.
GitHub("https://github.com/HMS-Core/hms-cordova-plugin") is the official repository for these plugins, You can open an issue or submit your ideas.
Huawei Developer Forum("https://forums.developer.huawei.com/forumPortal/en/home?fid=0101187876626530001") HMS Core Module is great for general questions, or seeking recommendations and opinions.
Huawei Developer Docs("https://developer.huawei.com/consumer/en/doc/overview/HMS-Core-Plugin") 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("https://github.com/HMS-Core/hms-cordova-plugin") repository.
Can we use this plugin in Ionic Framework ?

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?

Beginner: Integration of Huawei Kits (Account Kit, Ads Kit and Site Kit) to build Food app in Android (Kotlin)

Overview
In this article, we can learn how to integrate Account Kit, Ads Kit and Site kit in food applications. Account Kit guides you to login through the Huawei sign in button. Ads Kit will advertise on the application. Site Kit guides you to select the places or locations. Mobile apps make our world better and easier customer to prefer comfort and quality instead of quantity.
This article will guide you to show favourite hotels or nearby hotels.
Prerequisites
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.
Integration Preparations
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. On right-upper corner of android project click Gradle, choose Project Name > app > Tasks > android, and then click signingReport, as follows.
{
"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"
}
Note: Project Name depends on the user created name.
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, as follows.
7. Enter SHA-256 certificate fingerprint and click
, as follows.
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and Enable required kits (Account Kit and Site Kit).
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
implementation 'com.huawei.hms:ads-lite:13.4.40.301'
implementation 'com.huawei.hms:site:5.2.0.300
11. Now Sync the gradle.
12. Add the below permissions in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Account Kit Overview
Huawei Account Kit provides for developers with simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on Sign in with Huawei ID button to quickly and securely sign in to the app. We can implement authorization code sign in use case to login to application.
Signing with Authorization Code
In this method, Account kit allows to sign-in using an ID in authorization code mode. When you click the Huawei ID signing in button, it requires the AccountAuthParams and create a service with authParams, then add startActivityForResult() method in Huawei ID signing in button with service and requestCode.
Find the below code to get this method.
val authParams : AccountAuthParams = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams()
val service : AccountAuthService = AccountAuthManager.getService([email protected], authParams)
startActivityForResult(service.signInIntent, 1002)
When the user clicks login with Huawei ID button, the app needs to authorize and login operations from the user.
Find the below code to get the result.
override fun onActivityResult(requestCode: kotlin.Int, resultCode: kotlin.Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1002) {
//login success
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
val authAccount = authAccountTask.result
Toast.makeText(this, "signIn get code success." + authAccount.authorizationCode,
Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "signIn get code failed: "+ (authAccountTask.exception as ApiException).statusCode,
Toast.LENGTH_LONG).show()
}
}
}
Add the below code in activity_main.xml
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id="@+id/btn_signin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/Huawei_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="70sp"
android:layout_marginBottom="5dp"
android:background="#3b5998"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:visibility="visible"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_corner_radius="hwid_corner_radius_small" />
Result
Sign Out
Use this service to sign out the user from application.
Find the below code.
val signOutTask = service.signOut()
signOutTask?.addOnSuccessListener {
Toast.makeText(this, "signOut Success", Toast.LENGTH_LONG).show()
}?.addOnFailureListener {
Toast.makeText(this, "signOut fail", Toast.LENGTH_LONG).show()
}
Result
Ads Kits Overview
Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Banner Ads in this application.
Banner Ads are rectangular ad images located at the top, middle or bottom of an application’s layout. Banner ads are automatically refreshed at intervals. When a user clicks a banner ad, in most cases the user will guide to the advertiser’s page.
Standard Banner Ad Dimensions
The following table lists the standard banner ad dimensions.
Read full article in forum
Tips and Tricks
Make sure you are already registered as Huawei developer.
Enable Account kit and Site kit service in the App Gallery.
Make sure your HMS Core is latest version.
Make sure you have added the agconnect-services.json file to app folder.
Make sure you have added SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Banner ads be can also added programmatically.
Conclusion
In this article, we have learnt integration of Account Kit, Ads Kit and Site Kit in food applications. It will guide you to show favourite hotels or nearby hotels based on the user selection.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
References
Account Kit
Banner Ads Kit
Site Kit
Read full article in forum
shikkerimath said:
Overview
In this article, we can learn how to integrate Account Kit, Ads Kit and Site kit in food applications. Account Kit guides you to login through the Huawei sign in button. Ads Kit will advertise on the application. Site Kit guides you to select the places or locations. Mobile apps make our world better and easier customer to prefer comfort and quality instead of quantity.
This article will guide you to show favourite hotels or nearby hotels.
Prerequisites
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.
Integration Preparations
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. On right-upper corner of android project click Gradle, choose Project Name > app > Tasks > android, and then click signingReport, as follows.
View attachment 5292145
Note: Project Name depends on the user created name.
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, as follows.
View attachment 5292147
7. Enter SHA-256 certificate fingerprint and click
, as follows.
View attachment 5292149
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
8. Click Manage APIs tab and Enable required kits (Account Kit and Site Kit).
View attachment 5292153
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.300'
implementation 'com.huawei.hms:hwid:5.2.0.300'
implementation 'com.huawei.hms:ads-lite:13.4.40.301'
implementation 'com.huawei.hms:site:5.2.0.300
11. Now Sync the gradle.
12. Add the below permissions in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Account Kit Overview
Huawei Account Kit provides for developers with simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on Sign in with Huawei ID button to quickly and securely sign in to the app. We can implement authorization code sign in use case to login to application.
Signing with Authorization Code
In this method, Account kit allows to sign-in using an ID in authorization code mode. When you click the Huawei ID signing in button, it requires the AccountAuthParams and create a service with authParams, then add startActivityForResult() method in Huawei ID signing in button with service and requestCode.
Find the below code to get this method.
val authParams : AccountAuthParams = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams()
val service : AccountAuthService = AccountAuthManager.getService([email protected], authParams)
startActivityForResult(service.signInIntent, 1002)
When the user clicks login with Huawei ID button, the app needs to authorize and login operations from the user.
Find the below code to get the result.
override fun onActivityResult(requestCode: kotlin.Int, resultCode: kotlin.Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1002) {
//login success
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
val authAccount = authAccountTask.result
Toast.makeText(this, "signIn get code success." + authAccount.authorizationCode,
Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "signIn get code failed: "+ (authAccountTask.exception as ApiException).statusCode,
Toast.LENGTH_LONG).show()
}
}
}
Add the below code in activity_main.xml
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id="@+id/btn_signin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/Huawei_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="70sp"
android:layout_marginBottom="5dp"
android:background="#3b5998"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:visibility="visible"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_corner_radius="hwid_corner_radius_small" />
Result
View attachment 5292159
Sign Out
Use this service to sign out the user from application.
Find the below code.
val signOutTask = service.signOut()
signOutTask?.addOnSuccessListener {
Toast.makeText(this, "signOut Success", Toast.LENGTH_LONG).show()
}?.addOnFailureListener {
Toast.makeText(this, "signOut fail", Toast.LENGTH_LONG).show()
}
Result
View attachment 5292163
Ads Kits Overview
Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Banner Ads in this application.
Banner Ads are rectangular ad images located at the top, middle or bottom of an application’s layout. Banner ads are automatically refreshed at intervals. When a user clicks a banner ad, in most cases the user will guide to the advertiser’s page.
Standard Banner Ad Dimensions
The following table lists the standard banner ad dimensions.
Read full article in forum
Tips and Tricks
Make sure you are already registered as Huawei developer.
Enable Account kit and Site kit service in the App Gallery.
Make sure your HMS Core is latest version.
Make sure you have added the agconnect-services.json file to app folder.
Make sure you have added SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Banner ads be can also added programmatically.
Conclusion
In this article, we have learnt integration of Account Kit, Ads Kit and Site Kit in food applications. It will guide you to show favourite hotels or nearby hotels based on the user selection.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
References
Account Kit
Banner Ads Kit
Site Kit
Read full article in forum
Click to expand...
Click to collapse
can we get phone and email address in Account kit

Implement Realistic 3D Rendering in Three Steps

The conventional method of rendering a 3D model and scene with realistic materials is often tedious, making it difficult to standardize into several, simple steps.
Let's see what this process requires:
First, a rich array of texture maps and material images should be prepared according to how detailed and complex the model and scene are. The more complex they are, the more time-consuming the process of collecting such maps and images will be. Of course you can turn to those available on the market, but they could be expensive.
Second, parameters that have to be created from scratch. Most 3D modeling programs require abundant parameters for rendering, and setting or controlling models via parameter adjustment.
Third, work experience. The demand for 3D modelers is increasing, emphasizing the skills and work experience necessary for 3D modeling. As models and scenes are becoming more diverse and delicate, the modeler has a bigger influence over the quality of the models.
Indeed, such requirements — if met — lead to a desirable result. They, however, are also daunting.
Fortunately, there is now an easier solution to this with the material generation capability from 3D Modeling Kit, which is easy-to-use and can create high-quality materials in just three steps.
{
"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"
}
​The image on the left shows a complex scene containing multiple objects. Such a scene is common to see in a 3D game. To render it with materials, we just need to:
1. Use an RGB camera to collect images of real materials.
2. Input the images for material generation, which automatically generates the texture maps.
3. Use the maps for rendering.
​The material generation capability from 3D Modeling Kit utilizes AI to streamline and simplify the strenuous process of material generation and rendering, to improve the efficiency of creating 3D models at a lower cost. Specifically speaking, this capability offers the template materials that are created from the experience and material creation specifications of technical artists, to make such valuable assets reusable.
Introduction to Material Generation​
This capability enables your users to turn one or more RGB images into four physically based rendering (PBR) texture maps (the diffuse map, normal map, specular map, and roughness map), with just a tap, to help create true-to-life materials. This capability utilizes AI to create 3D materials for commercial use.
Specifications
Software and hardware requirements: an Android device with a standard RGB camera, instead of an RGB-D or light detection and ranging (LiDAR) sensor
Supported material types: concrete, marble, rock, gravel, brick, gypsum, clay, metal, wood, bark, leather, fabric, paint, plastic, composite material, and ground (including grass and sand)
Supported input images: have a resolution within the range of 1K to 4K, containing no seam, light spot, shade, or reflection.
Output texture maps: have a resolution of 1K (1024 x 1024 px) or 2K (2048 x 2048 px).
SDK size: 88 KB
Accuracy (SSIM): > 0.9
Application scenarios: The powerful material generation capability can be adopted in a wide range of scenarios, for example:
E-commerce: Use this capability to create 3D product models, delivering a more immersive online shopping experience to users.
Exhibition: Display lifelike 3D models of valuable items such as cultural exhibits.
Game: Create realistic wooden floors, tables, and walls for indoor scenes, to better immerse players.
Development Preparations​Integrating the HMS Core SDK​Add the AppGallery Connect configuration file of your app.
Add the agconnect-services.json file to your app after you have enabled 3D Modeling Kit.
Step 1. Sign in to AppGallery Connect and click My projects.
Step 2. Find your project and click the app that needs to integrate the HMS Core SDK.
Step 3. Go to Project settings > General information. In the App information area, click agconnect-services.json to download the configuration file.
Step 4. Copy the file to the app's root directory.
​Configuring the Maven Repository Address for the HMS Core SDK
Step 1. Open the project-level build.gradle file of your Android Studio project.
Step 2. Add the AppGallery Connect plugin and the Maven repository.
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
Go to buildscript > dependencies and add the AppGallery Connect plugin configuration, if the agconnect-services.json file has been added to the app configuration, if the agconnect-services.json file has been added to the app.
Code:
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}
Note that the Maven repository address cannot be accessed from a browser. It can only be configured in the IDE. If there are multiple Maven repositories, add the Maven repository address of Huawei as the last one.
Adding Build Dependencies
Step 1. Open the app-level build.gradle file.
​Step 2. Add build dependencies in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:modeling3d-material-generate:{version}'
}
Note: Replace {version} with the actual SDK version number. For details about the version number, please refer to Version Change History.
For example: implementation 'com.huawei.hms:modeling3d-material-generate:1.0.0.300'.
Step 3. Add the AppGallery Connect plugin configuration in either of the following methods:
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration.
id 'com.huawei.agconnect'
}
Defining Multi-language Settings​
If your app supports all the languages supported by the HMS Core SDK, skip the operation procedure in this section.
If your app supports only some of these languages, follow the operation procedure in this section to complete the required configuration.
a. Open the app-level build.gradle file.
b. Go to android > defaultConfig, add resConfigs, and configure the supported languages as follows:
Code:
android {
defaultConfig {
...
resConfigs "en", "zh-rCN", "Other languages supported by your app"
}
}
For details about the languages supported by the HMS Core SDK, please refer to Languages Supported by the HMS Core SDK.
Synchronizing the Project​After completing the preceding configuration, click the synchronization icon on the toolbar to synchronize the Gradle files.
​If an error occurs, check the network connection and the configuration in the build.gradle files.
Configuring Obfuscation Scripts​Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Step 1. Open the app-level obfuscation configuration file proguard-rules.pro of your project and add configurations to exclude the HMS Core SDK from obfuscation.
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
Adding Permissions​To use the material generation capability, declare the following permissions in the AndroidManifest.xml file:
Code:
<!-- Write texture map files to storage and read data to be processed from storage. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Connect to Internet for uploading images or downloading texture maps. -->
<uses-permission android:name="android.permission.INTERNET" />
Development Procedure​Before developing your app, you need to make necessary preparations. Ensure that the Maven repository address for the HMS Core SDK has been configured in your project, and the SDK of this service has been integrated.
1.Set an access token or use the API key in agconnect-services.json during app initialization for your app authentication.
(Recommended) Use the setAccessToken method to set an access token during initialization when the app is started. The access token does not need to be set again.
Code:
MaterialGenApplication.getInstance().setAccessToken("your AccessToken");
For details about how to obtain the access token, please refer to "Client Credentials" in OAuth 2.0-based Authentication.
Use the setApiKey method to set an API key during initialization when the app is started. The API key does not need to be set again.
Code:
MaterialGenApplication.getInstance().setApiKey("your api_key");
When you create an app in AppGallery Connect, an API key will be assigned to your app.
2.Create a material generation engine and configurator, and initialize the engine.
Code:
// Create a material generation engine and pass the current context.
Modeling3dTextureEngine engine = Modeling3dTextureEngine.getInstance(context);
// Create a material generation configurator.
Modeling3dTextureSetting setting = new Modeling3dTextureSetting.Factory()
// Set the working mode to AI.
.setTextureMode(Modeling3dTextureConstants.AlgorithmMode.AI)
.create();
3.Create a listener callback to process the image upload result.
Code:
Modeling3dTextureUploadListener uploadListener = new Modeling3dTextureUploadListener() {
public void onResult(String taskId, Modeling3dTextureUploadResult result, Object ext) {
// Obtain the image upload result.
if (result.isComplete()) {
// Process the upload result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during upload.
}
@Override
public void onUploadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
4.Upload the collected images to the cloud.
Code:
// Obtain the ID of a material generation task and pass it to the configurator.
Modeling3dTextureInitResult modeling3dTextureInitResult = engine.initTask(setting);
String taskId = modeling3dTextureInitResult.getTaskId();
if (taskId == null || taskId.equals("")) {
Log.e("", "get taskId error " + modeling3dTextureInitResult.getRetMsg());
} else {
// Set the upload listener.
engine.setTextureUploadListener(uploadListener);
// Upload the images in asynchronous mode, passing the task ID and directory of the images.
engine.asyncUploadFile(taskId, filePath);
}
5.Query the progress of an on-cloud material generation task.
Code:
// Create a material generation task processing instance and pass the current context.
Modeling3dTextureTaskUtils taskUtils = Modeling3dTextureTaskUtils.getInstance(context);
// Query the material generation progress.
Modeling3dTextureQueryResult queryResult = taskUtils.queryTask(taskId);
6.Create a listener callback to process the download result of generated texture maps.
Code:
Modeling3dTextureDownloadListener downloadListener = new Modeling3dTextureDownloadListener() {
public void onResult(String taskId, Modeling3dTextureDownloadResult result, Object ext) {
// Obtain the download result of generated texture maps.
if (result.isComplete()) {
// Process the download result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during download.
}
@Override
public void onDownloadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
7.Download the generated texture maps.
Code:
// Set the download listener.
engine.setTextureDownloadListener(downloadListener);
// Download the texture maps, passing the task ID and texture map path.
engine.asyncDownloadTexture(taskId, savePath);
8.Call the synchronous API to obtain the generated texture maps in real time.
Code:
// Call the synchronous API, passing the image file path, texture map path, and configurator.
int result = engine.syncGenerateTexture(filePath, downloadPath, setting);
9.Delete the material generation task.
Code:
int ret = taskUtils.deleteTask(taskId);
Amazing capability, right? To learn more about 3D Modeling Kit, check out:
References
Official website of 3D Modeling Kit
Development guide to the kit
HMS Core section on HUAWEI Developer Forum
GitHub and Gitee to obtain the open-source code for the kit
Stack Overflow where you can find solutions to integration-related problems

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

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

Categories

Resources