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 ?
Related
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?
This article includes information about how to integrate Huawei Cordova Account plugin to a Cordova project and how to use some APIs that Huawei Account Kit provides.
{
"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 Cordova Account plugin provides adaption code used for the HUAWEI Account Kit to use in Cordova platform. HUAWEI Account Kit enables developers to use simple, secure, and quick sign-in and authorization functions to save time from long authorization periods and it’s two factor authentication(password authentication and mobile number authentication) process keeps users informations safe.
Service Features
· Quick and standard
Huawei Account Kit allows you to connect to the Huawei ecosystem using your HUAWEI ID from a range of devices. This range of devices is not limitted with mobile phones, you can also easily access applications on tablets, wearables, and smart displays by using Huawei ID.
· Massive user base and global services
Huawei Account Kit serves 190+ countries and regions worldwide. Users can also use HUAWEI ID to quickly sign in to apps. For details about supported regions/countries please refer here from official documentation.
· Secure, reliable, and compliant with international standards
Complies with international standards and protocols (such as OAuth2.0 and OpenID Connect), and supports two-factor authentication to ensure high security.
Integrating Huawei Account Kit to a Cordova Project
Preperations
1. You should prepare your development environment by following “Preparing the Development Environment” guide from official documentation.
2. To be able to use Huawei Cordova Account Plugin you shoud register as a Huawei developer and follow “Configuring App Information in AppGallery Connect” guide from official documentation.
Integrating Cordova Account Plugin
1- You can install the plugin through npm.
· Run the following command in the root directory of your Cordova project to install it through npm.
Code:
cordova plugin add @hmscore/cordova-plugin-hms-account
2- You should check if the Cordova Account Plugin successfully added to “plugin” folder of the root directory of your cordova project.
3- You should add agconnect-services.json(downloaded from AppGallery Connect), jks and build.json files to your projects root directory.
· Please refer following code snippet for build.json file.
Code:
{
"android": {
"release": {
"keystore": "./xxx.jks",
"storePassword": "xxxxx",
"alias": "xxx",
"password": "xxxxx"
},
"debug": {
"keystore": "./xxx.jks",
"storePassword": "xxxxx",
"alias": "xxx",
"password": "xxxxx"
}
}
}
Now the integration part is done and you are ready to use the Cordova Account Plugin in your Cordova project.
Use Cordova Account Plugin APIs
Signing-In with Huawei ID
To allow users securely signing-in with Huawei ID, you should use signIn method of HMSAccount module. When this method called for the first time for a user, a Huawei ID authorization interface will be shows up and user should click “Authorize and Login” button with necessary permission checks. After signing in for the first time, when users try to sign in again, the authorization screen will not show up again, unless they revoke the authorization.
Code:
const jsonArr = [CommonTypes.ScopeConstants.SCOPE_AUTHORIZATION_CODE];
const param = CommonTypes.HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM;
try {
const res = await HMSAccount.signIn(jsonArr, param);
alert(JSON.stringify(res));
} catch (ex) {
alert(JSON.stringify(ex));
}
When sign-in operation is successfull, user information will be returned as AuthHuaweiID object, otherwise an exception will be returned.
Signing-Out from Huawei ID
signOut method is used to allow user signing-out from Huawei ID. But it does not clear user information permenantly. The authorization information is not cleared, so when signIn method called again the application will not interact with the authorization interface.
Code:
try {
const res = await HMSAccount.signOut();
alert("signOut -> success");
} catch (ex) {
alert('signOut -> Error : ' + JSON.stringify(ex));
}
If the user signed out successfully, the promise is resolved . Otherwise it is rejected.
Silently Signing-In with Huawei ID
Authorization is required only at the first sign-in to your app using a HUAWEI ID. The silentSignIn method allows to using the same HUAWEI ID without authorization for subsequent sign-ins.
Code:
try {
const res = await HMSAccount.silentSignIn();
alert("silentSignIn -> success :" + JSON.stringify(res));
} catch (ex) {
alert('silentSignIn -> Error : ' + JSON.stringify(ex));
}
In case of silentSignIn is successfull, user information will be returned via a AuthHuaweiId object. Otherwise exception object is returned.
Canceling Huawei ID Authorization
To improve privacy and security, users are allowed to revoke authorization on your app. As mentioned before, when user firstly signing-ins, a Huawei ID authorization interface will be shows up. But for other calls of signIn method, the authorization interface will not be shows up because authorization information is not deleted with signOut method call or others. To clear authorization information cancelAuthorization method should be called and revoke authorization.
Code:
try {
const res = await HMSAccount.cancelAuthorization();
alert("cancelAuthorization -> success");
} catch (ex) {
alert('cancelAuthorization -> Error : ' + JSON.stringify(ex));
}
If the user cancels an authorization successfully, the promise will be resolved and authorization information will be deleted; otherwise exception object will be returned.
Automatically Retrieving SMS Verification Code
To allow your app to use SMS verification and verify the user identity using an SMS verification code you should integrate the HMSReadSmsManager module of Huawei Cordova Account Plugin. Without any need to apply for the SMS read permission, your app can automatically read the SMS verification code when this module is used.
Code:
try {
const res = await HMSReadSMSManager.smsVerificationCode();
alert("smsVerificationCode -> success :" + JSON.stringify(res));
} catch (ex) {
alert('smsVerificationCode -> Error : ' + JSON.stringify(ex));
}
After smsVerificationCode method of HMSReadSmsManager module called, app starts to listen right formatted messages, and catch them. There is five minutes timing out period, if the right formatted message is catched in this period of time, message will be returned otherwise a time out message will be fundisplayed.
You should generate an SMS verification code based on the mobile number and send an SMS message to the user in a specific format.The specific format should be as follows;
· “prefix_flag”: Indicates the prefix flag of the SMS message, including <#>, [#], and \u200b\u200b (which is a string of invisible Unicode characters)
· “short message verification code is”: indicates the SMS message content that is changeable
· “XXXXXX”: indicates a verification code
· “hash_value”: indicates the hash value generated by the HMS Core SDK to uniquely identify the app.
The hash_value is unique for all apps, it is generated based on the app package name. To obtain this hash value you can use obtainHashCode method of HMSReadSmsManager module.
Code:
try { const res = await HMSReadSMSManager.obtainHashCode(); alert("hashCode -> success :" + JSON.stringify(res)); } catch (ex) { alert('hashCode -> Error : ' + JSON.stringify(ex)); }
Sample Sign-In/Sign-Out Application
With the help of the above information lets create a sample app which performs a basic sign-in operation to see how to use HMS Account Kit APIs.
Step 1: Lets follow instructions on “Integrating Huawei Account Kit to a Cordova Project” of this article to prepare development environment and integrate plugin to the sample project.
Step 2: Make sure that app creation and integration of the plugin successfull.
Step 3: Create a button for sign-in operation on index.html file.
Step 4: Call HMS Account Kit signIn API to allow user signing-in on index.js file.
Code:
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
document.getElementById('btn_sign_in_with_id_token').addEventListener('click', signInWithIdToken);
}
};
async function signInWithIdToken() {
const jsonArr = [CommonTypes.ScopeConstants.SCOPE_ID_TOKEN];
const param = CommonTypes.HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM;
HMSAccount.signIn(jsonArr, param).then( function(userInfo){
localStorage.setItem('userInfo', JSON.stringify(userInfo));
window.location = "login.html";
}).catch(function(){
alert('signIn -> Error : ' + JSON.stringify(ex));
});
}
app.initialize();
Step 5: After successfull sign-in operation, lets use user information and displat it on a user information page. For that lets create a new page as follows.
login.html file includes one button for sign-out and user information fields. These fields filling up with user information which came from sign-in response as seen below.
Code:
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
var data = {
getUserInfo: function() {
var userInfo = localStorage.getItem('userInfo');
console.log(userInfo);
return JSON.parse(userInfo);
}
}
var userDataObject=data.getUserInfo();
document.getElementById('btn_sign_out').addEventListener('click', signOut);
document.getElementById('userName').innerHTML = "User Name: " + userDataObject.givenName + " " + userDataObject.familyName;
document.getElementById('nickName').innerHTML = "Nick Name: " + userDataObject.displayName;
}
};
async function signOut() {
HMSAccount.signOut().then( function(){
if(confirm('HuaweiId Authorization will be also deleted!')){
HMSAccount.cancelAuthorization();
}
alert("signOut -> success");
window.location = "index.html";
}).catch(function(){
alert('signOut -> Error : ' + JSON.stringify(ex));
});
}
app.initialize();
Step 6: Run cordova project
If you need, you can find whole sample sign-in/sign-out project on github.
As it can be seen using Huawei Cordova Account Plugin is an easy way to provide users secure sign in operations. It also helps to save from time with one click sign in functionality.
What are the maximum lengths of access_token and refresh_token?
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
Hello everyone, in this article, I will show how to integrate Huawei Nearby Plugin to a Cordova project.
Prerequisites
You should install npm, Node.js and Cordova CLI on your PC.
Pre-Installation
Configuring App Information in AppGallery Connect
Before you get started, you must register as a HUAWEI developer and complete identity verification on HUAWEI Developers.
Click to expand...
Click to collapse
Firstly, lets create an AppGallery Connect Project.
Sign in to AppGallery Connect and select My projects.
Click Add project.
Enter a project name and click OK.
After the project is created, the Project settings page is displayed. Before you use development capabilities provided by AppGallery Connect, you need to add an app to your project first.
In section Project settings > General information, click Add app.
On the Add app page, enter app information.
On the Project settings page, enter SHA-256 certificate fingerprint and then download the configuration file agconnect-services.json for Android platform.
A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in the AppGallery Connect. You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial for the certificate generation. Perform the following steps after you have generated the certificate.
Click to expand...
Click to collapse
Enabling Service
To use HUAWEI Nearby Service on your app, you first need to enable the service.
Sign in to HUAWEI Developers and click Console in the upper right corner. Go to HMS API Services > My APIs, select the project for which you want to enable HUAWEI Nearby Service, and click Add API from library. The API Library page is displayed.
Click Nearby Service.
On the Nearby Service page, click Enable to enable HUAWEI Nearby Service.
Sign the HUAWEI Nearby Service Agreement.
When you click My projects on the home page of AppGallery Connect to create a project for the first time, a dialog box will be displayed to prompt you to sign the HUAWEI Nearby Service Agreement (for details, please refer to AppGallery Connect Service and Agreement). If you have agreed to the HUAWEI Nearby Service Agreement, no such a dialog box will be displayed after you click Enable. For details, please refer to AppGallery Connect Agreement Signing Guide.
Click to expand...
Click to collapse
Go to HMS API Services > My APIs. The Nearby Service API is displayed.
Pre-installation steps end here. Basically, we created an AppGallery Connect project and enabled the Nearby Service. We also saved the SHA-256 certificate fingerprint to the project.
Installation
Firstly, open a command line and create a new Cordova project.
Bash:
cordova create HMSNearbyDemo com.huawei.medium.nearbydemo HMSNearby
This command will create a new directory named as HMSNearbyDemo and a new project named as HMSNearby inside it. You can change names as you wish.
The widget id property in config.xml file must be same with client > package_name value in agconnect-services.json file.
Click to expand...
Click to collapse
Go to project directory and add the android platform to the project.
Bash:
cd HMSNearbyDemo
cordova platform add android
Now, you need to add Huawei Nearby Plugin to the project. Run the following command in the root directory of your project to install it through npm.
Bash:
cordova plugin add @hmscore/cordova-plugin-hms-nearby
Copy agconnect-services.json file to <project_root>/platforms/android/app directory. In our case, project_root is HMSNearbyDemo folder.
Add keystore(.jks) to your project’s root directory.
You can refer to 3rd and 4th steps of Generating a Signing Certificate Codelab tutorial page for generating keystore file.
Click to expand...
Click to collapse
Create a file named as build.json in project’s root directory and fill the file according to your keystore information as in example below.
JSON:
{
"android": {
"debug": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
},
"release": {
"keystore": "<keystore_file>.jks",
"storePassword": "<keystore_password>",
"alias": "<key_alias>",
"password": "<key_password>"
}
}
}
Huawei Nearby Plugin requires minimum sdk version 21. If your minimum sdk version is lower than 21, set it as 21 in config.xml file. Otherwise, you can skip this step.
XML:
...
<platform name="android">
...
<preference name="android-minSdkVersion" value="21" />
</platform>
Finally, build the project.
Bash:
cordova build android
Using Huawei Cordova Nearby Plugin
Initially, we should request missing permissions from the user.
JavaScript:
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
// ...
// we have requested all permissions.
HMSNearby.requestPermissions([
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH,
HMSNearby.HMSPermission.PERMISSION_BLUETOOTH_ADMIN,
HMSNearby.HMSPermission.PERMISSION_ACCESS_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_CHANGE_WIFI_STATE,
HMSNearby.HMSPermission.PERMISSION_ACCESS_COARSE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_ACCESS_FINE_LOCATION,
HMSNearby.HMSPermission.PERMISSION_READ_EXTERNAL_STORAGE,
HMSNearby.HMSPermission.PERMISSION_WRITE_EXTERNAL_STORAGE
]).then((res) => {
console.log("Request permissions result: " + res);
});
}
};
Now, all functionalities are ready to use. The Nearby Connection basic structure is shown in the image below. I will show you sample code parts for each step.
Starting Broadcasting
The sample code for starting broadcasting is as follows:
JavaScript:
async function startBroadcasting() {
try {
const name = 'NearbyBroadcast';
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startBroadcasting(name, serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
You can customize the name parameter.
Starting Scanning
The sample code for starting scanning is as follows:
JavaScript:
// starting scanning
async function startScan() {
try {
const serviceId = 'com.huawei.medium.nearbydemo';
await HMSNearby.startScan(serviceId, HMSNearby.Policy.POLICY_STAR);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
We need to register scan events. When a remote device is found or an already found device is lost, scan events will be triggered.
Registering Scan Events and Requesting Connection
Code part below sends a connection request to the remote device without asking the user when any device is found.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_FOUND, async (res) => {
console.log('listener :: EVENT_SCAN_ON_FOUND triggered: ' + JSON.stringify(res));
// request connect
const resRequest = await HMSNearby.requestConnect("NearbyScan", res.endpointId);
console.log("listener :: requestConnect: " + JSON.stringify(resRequest));
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_SCAN_ON_LOST, (res) => {
console.log('listener :: EVENT_SCAN_ON_LOST triggered: ' + JSON.stringify(res));
});
Registering Connection Events and Accepting Connection
When a connection established, both peers must accept the connection. Then, event EVENT_CONNECTION_ON_RESULT will be triggered with the success state.
JavaScript:
// registering connection events and accepting connection
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_ESTABLISH, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_ESTABLISH triggered: ' + JSON.stringify(res));
// Accept the connection request without notifying user.
HMSNearby.acceptConnect(res.endpointId);
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_RESULT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_RESULT triggered: ' + JSON.stringify(res));
if (res.statusCode == HMSNearby.StatusCode.STATUS_SUCCESS) {
// The connection was established successfully, we can exchange data.
}
});
Registering Data Events and Sending Data
We connected to remote peer successfully. Now, we can send any data to peer.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_RECEIVED, (res) => {
console.log('listener :: EVENT_DATA_ON_RECEIVED triggered');
if (res.dataType === HMSNearby.DataType.DATA_BYTES) {
const receivedBytes = res.data;
// data as number array
}
});
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_DATA_ON_TRANSFER_UPDATE, async (res) => {
console.log('listener :: EVENT_DATA_ON_TRANSFER_UPDATE triggered: ' + JSON.stringify(res));
if (res.status === HMSNearby.TransferState.TRANSFER_STATE_SUCCESS) {
console.log('listener :: data transfer success');
}
});
try {
const bytes = [11, 22, 33, 44]; // any data in number array
const endpointIds = ['endpointId1', 'endpointId2']; // remote endpoint id list
await HMSNearby.sendBytes(bytes, endpointIds);
} catch(ex) {
alert(JSON.stringify(ex));
}
Disconnection
After all operations are done, we should simply call disconnect method. When a peer calls disconnect, event EVENT_CONNECTION_ON_DISCONNECT will be triggered on the other peer’s device.
JavaScript:
HMSNearby.registerEvent(HMSNearby.HMSNearbyEvent.EVENT_CONNECTION_ON_DISCONNECT, (res) => {
console.log('listener :: EVENT_CONNECTION_ON_DISCONNECT triggered: ' + JSON.stringify(res));
});
async function disconnect() {
try {
const endpointId = 'endpointId';
await HMSNearby.disconnect(endpointId);
} catch(ex) {
alert(JSON.stringify(ex));
}
}
Conclusion
In this article, I integrated HMS Nearby Plugin to a Cordova project and showed the basic functionalities of Nearby Connection. I tried to explain connecting to peer, transferring data and disconnection functionalities with examples.
Thank you for reading, I hope it was helpful.
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.
Introduction
In this article, we will be learning how to integrate the Huawei Site kit and Cloud DB integrations in Android using Kotlin. Using AGC Cloud DB service, Service Providers from multiple cities can manage their data through CRUD (Create, Read, Update and Delete) operations. Using Site Kit user can search nearby stores and check stores details.
Development Overview
You need to install Android Studio and I assume that you have prior knowledge about the Android and Kotlin
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later
Android studio installed.
HMS Core (APK) 4.x or later
Integration of Site Kit
Site Kit provides place search services including keyword search, nearby place search, place detail search, and place search suggestion, helping your app provide convenient place-related services to attract more users and improve user loyalty.
Step 1: To integrate Site kit, need to add the below library:
Code:
implementation 'com.huawei.hms:site:5.0.2.300’
Step 2: How to get API Key?
Create an app in AppGallery Connect enter all necessary information.
Generate and configure the signing certificate fingerprint.
Add the AppGallery Connect plug-in and the Maven repository in the project-level build.gradle file. Configure the signature file in Android Studio.
For details, refer to Preparations for Integrating HUAWEI HMS Core.
After configure project, you can find API key in below image.
{
"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"
}
Step 3: To initialize HMS Site kit:
searchService = SearchServiceFactory.create(this, Utils.getApiKey())
To fetch nearby stores based on user’s current location:
SearchServiceActivity.kt
Code:
intent.let {
val request = NearbySearchRequest().apply {
queryString=it.getStringExtra(AppConstants.REQUEST_QUERY).toString()
setQuery(queryString)
setLocation(
Coordinate(
it.getDoubleExtra(AppConstants.SERVICE_LAT_KEY, 0.0),
it.getDoubleExtra(AppConstants.SERVICE_LNG_KEY, 0.0)
)
)
}
imageString = it.getStringExtra(AppConstants.PROVIDER_IMAGE_KEY).toString()
searchService?.nearbySearch(request, searchResultListener)
}
Results
Note: For more details, refer Site kit integration procedure. Site kit- SDK integration
Integration of Cloud DB
In this scenario, we can learn about a database service that runs on a cloud and is accessible from anywhere. Find the following points for better understand:
How to use Cloud DB to develop applications?
How to read, write and query application data to Cloud DB?
This service provides the synergy database product that provides data synergy management capabilities between the device and the cloud, unified data models, and various data management APIs.
Cloud DB supplies us simply cloud database and our project work together successfully and we can take advantages of CRUD (Create, Read, Update and Delete) operations.
Prerequisites
To use the Cloud DB for build application service, you need to complete the following preparations:
You have registered an account on the AppGallery Connect console and passed real-name authentication.
You have created a project and application on the AppGallery Connect console.
You have enabled the Anonymous account authentication service for the application to use permissions of the authentication user.
You have installed Android Studio on the local host.
Enable Cloud DB Service
Before using the Cloud DB service, you need to enable it.
Log in to AppGallery Connect and click My Projects.
Select a project from the project list and click an app for which you need to enable the Cloud DB service.
In the navigation bar, choose Build > Cloud DB.
Click Enable now to enable the Cloud DB service.
Select the Data storage location.
After the service is initialized, the Cloud DB service is enabled successfully.
After the service is initialized, the Cloud DB service is enabled successfully.
Adding and Exporting Object Types
The following example shows how to create object types on the AppGallery Connect console and export the object type file in the Java format for Android application development.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add an object type.
3. In the navigation bar, choose Build > Cloud DB.
4. Click Add to navigate to the object type creation page.
5. Set Object Type Name to LoginInfo, and click Next.
6. Click “+Add Field”, add the fields as per your requirements and click Next.
7. (Optional) Click “+Add Index”.
8. Add permissions as follows and click Next. (For Everyone, upsert and delete access is not allowed).
9. Click OK. Object types are created and displayed in the object type list.
The created object types are displayed in the object type list.
Repeat the above steps to create to create multiple table.
10. Click “Export” button
11. Set the format of the file to be exported to JAVA.
12. Set the Java file type to Android.
13. Enter the package name in the JAVA file.
The package name can contain only the following three types:
Letters: A–Z or a–z, which are mandatory
Digits: 0–9
Special characters: underscore (_) and period (.)
15. Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project. The file that contains all object types in the version is exported to the local PC. The exported Java file will be added to the local development environment in subsequent steps.
Cloud DB Zone
You can create a Cloud DB zone on the AppGallery Connect console. Perform the following steps to set Cloud DB Zone Name.
1. Log in to AppGallery Connect and click My projects.
2. Select a project from the project list and click an app for which you need to add a Cloud DB zone.
3. In the navigation tree, choose Build > Cloud DB.
4. Click the Cloud DB Zones tab.
5. Click Add to go to the Cloud DB zone creation page.
6. Enter Your App Name in the Cloud DB Zone Name text box.
7. Click OK the created Cloud DB zones are displayed in the Cloud DB zone list.
Configuring the Development Environment
Add a Cloud DB SDK to the dependencies node in the build.gradle file in the Project/app directory.
Code:
implementation <strong>'com.huawei.agconnect:agconnect=database:1.2.3.301’</strong>
In the build.gradle file, set the compatibility mode of Java source code to JDK1.8.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
Adding Object Type Files
During application development, you can directly add the JAVA files exported from the AppGallery Connect console to the local development environment, and use the createObjectType() method in the AGConnectCloudDB class to define and create object types. Then you do not need to create object types for local application development.
Add all exported files to the local development environment.
Initialize Cloud DB. Use the createObjectType() method in the AGConnectCloudDB class to define and create object types.
Initializing
After adding an object type file, you can use the Cloud DB to develop an application. When developing an application, you need to initialize AGConnectCloudDB, and create Cloud DB zone and object types.
Initialize AGConnectCloudDB in an application’s CloudDBZoneWrapper
Code:
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
Obtain the AGConnectCloudDB instance and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance();
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
Create the Cloud DB zone configuration object and open the Cloud DB zone. Add the below code in CloudDBZoneWrapper class.
Code:
public void openCloudDBZoneV2() {
mConfig = new CloudDBZoneConfig(AppConstants.URBAN_HOME_SERVICES,
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
openDBZoneTask.addOnSuccessListener(cloudDBZone -> {
Log.w(TAG, "open clouddbzone success");
mCloudDBZone = cloudDBZone;
// Add subscription after opening cloudDBZone success
mUiCallBack.onInitCloud();
addSubscription();
}).addOnFailureListener(e ->
Log.w(TAG, "open clouddbzone failed for”));
}
Writing Data
You can use the executeUpsert() API to write one object or a group of objects to the current Cloud DB zone.
Add the below code in CloudDBZoneWrapper class.
Code:
public void insertDbZoneInfo(T objectInfo) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> upsertTask = mCloudDBZone.executeUpsert(objectInfo);
upsertTask.addOnSuccessListener(cloudDBZoneResult -> {
mUiCallBack.onInsertSuccess(cloudDBZoneResult);
}).addOnFailureListener(e -> {
mUiCallBack.updateUiOnError("Insert table info failed");
});
}
Viewing Data
Data added on the application page will be stored on the cloud. After a listener for data changes is registered on the device, the device will be notified when there is any changes on the cloud, and the local data will be updated in time.
You can use the query condition together with the subscribeSnapshot() method to specify an object to be listened on. When the data of the object is changed, the device will be notified and the original data stored on the cloud will be synchronized to the device based on the data changes information obtained by snapshots.
Add the below code in CloudDBZoneWrapper class.
Code:
private OnSnapshotListener<T> mSnapshotListener = (cloudDBZoneSnapshot, e) -> {
if (e != null) {
Log.w(TAG, "onSnapshot" );
return;
}
CloudDBZoneObjectList<T> snapshotObjects = cloudDBZoneSnapshot.getSnapshotObjects();
List<T> dbZoneList = new ArrayList<>();
try {
if (snapshotObjects != null) {
while (snapshotObjects.hasNext()) {
T objectInfo = snapshotObjects.next();
dbZoneList.add(objectInfo);
}
}
mUiCallBack.onSubscribe(dbZoneList);
} catch (AGConnectCloudDBException snapshotException) {
Log.w(TAG, "onSnapshot:(getObject)");
} finally {
cloudDBZoneSnapshot.release();
}
};
Querying Data
The executeQuery(), addOnSuccessListener(), and addOnFailureListener() methods are used together to query data in asynchronous mode.
Add the below code in CloudDBZoneWrapper class.
Code:
public void queryAllData(CloudDBZoneQuery<T> query) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<CloudDBZoneSnapshot<T>> queryTask = mCloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<T>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<T> snapshot) {
processQueryResult(snapshot);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
mUiCallBack.updateUiOnError("Query failed");
}
});
}
Deleting Data
You can use the executeDelete() method to delete a single object or a group of objects. When deleting data, Cloud DB will delete the corresponding data based on the input object primary key and does not check whether other attributes of the object are consistent with the stored data. When a group of objects are deleted, the deletion operation is atomic. That is, objects in the list are either all deleted successfully or all fail to be deleted.
Add the below code in CloudDBZoneWrapper class.
Code:
public void deleteTableData(List<T> tableObject) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
Task<Integer> deleteTask = mCloudDBZone.executeDelete(tableObject);
if (deleteTask.getException() != null) {
mUiCallBack.updateUiOnError("Delete service type table failed");
return;
}
mUiCallBack.onDelete(tableObject);
}
}
Editing Data
You can use the editService() method to edit professional’s details.
Add the below code in ManageServiceActivity.kt class.
Code:
override fun editService(listObject: ServiceType) {
val intent = Intent(this, AddServiceActivity::class.java)
intent.apply {
putExtra(AppConstants.CATEGORY_NAME, listObject.cat_name)
putExtra(AppConstants.PROVIDER_PH_NUM, listObject.phone_number.toString())
putExtra(AppConstants.PROVIDER_MAIL_ID, listObject.email_id)
putExtra(AppConstants.PROVIDER_COUNTRY, listObject.country)
putExtra(AppConstants.PROVIDER_ID, listObject.id)
putExtra(AppConstants.PROVIDER_NAME, listObject.service_provider_name)
putExtra(AppConstants.PROVIDER_CITY, listObject.city)
putExtra(AppConstants.PROVIDER_STATE, listObject.state)
}
startActivity(intent)
}
Results
Tips and Tricks
Always use the latest version of the library.
Always provide proper Roles to user in Object Types.
Note: For more details, please refer Cloud Db service integration documentation, Cloud DB- Introduction
Conclusion
By using Cloud DB you can connect with Database without the need of APIs. You can perform the CRUD operations and also can restrict user access for the tables. Easy to connect with the application. Also you can search nearby service (plumber, electrician, painter etc) using site kit like as etc.
Site Kit to fetch nearby stores.
Cloud DB service to add, delete and edit professional’s details.
References
Site Kit
Cloud DB- Applying for Cloud BD
Cloud DB- Introduction
Checkout in forum