{
"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.
Related
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 ?
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?
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
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:
Java:
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:
Java:
searchService = SearchServiceFactory.create(this, Utils.getApiKey())
To fetch nearby stores based on user’s current location:
SearchServiceActivity.kt
Java:
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.
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.
Java:
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.
Java:
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
Java:
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
Obtain the AGConnectCloudDB instance and create object types.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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.
Java:
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
Read In Forum
Does CloudDB supports offline operations ?
What is the max size of data to be stored on Cloud DB?
{
"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"
}
Analytics
Analytics is a technique which is widely used in businesses today. It is essential for almost all the organizations to track the progress, user interactions and plan for the measures.
There are plenty of services available in the market which provides the access to assess the data and provide analysis report. I came across such service and tried to work on it. The results of the service are quite stable and quick.
I am talking about Huawei Analytics Kit.
Huawei Analytics kit offers data focused on intelligent decision making.
Huawei Analytics kit provides fast integration and convenient data collection.
Advantages
Simple and quick integration
Secure data-related services
Fast and convenient data collection
Real-time, comprehensive and intelligent analysis
Comprehensive user profiles
Assistance in effectively reaching users.
Push Service
Push services are widely used message sending/broadcasting service.
Which has many different ways and events to apply for different requirements.
Huawei Push kit offers different kind of message sending options as
Push Notification
Data Messages
We will be focusing on the Data Message in this article.
Data Messages
Data messages are data payloads which are handled at the device.
You can customize them in the form of key-value pair.
Use Case
This article will focus on the integration of Analytics and Push kit in the Task Scheduler application and will be showcasing how this can be helpful for the user to improve their businesses.
Development Overview
Prerequisite
1. Must have a Huawei Developer Account
2. Must have Android Studio 3.0 or later
3. Must have a Huawei phone with HMS Core 5.0.2.300 or later
4. EMUI 9.1.0 or later
Software Requirements
1. Java SDK 1.7 or later
2. Android 5.0 or later
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the Analytics and Push Kit API.
3. Download the agconnect-services.json file.
4. Create an Android project.
Integration
1. Add below to build.gradle (project) file, under buildscript/repositories and allprojects/repositories.
Maven {url 'http://developer.huawei.com/repo/'}
2. Add below to build.gradle (app) file, under dependencies to use the Analytics and Push kit SDK.
Code:
dependencies{
// Import the Push SDK.
implementation 'com.huawei.hms:push:5.1.1.301'
Import the Analytics, please add Analytics SDK
implementation 'com.huawei.hms:hianalytics:5.2.0.300'
}
Tip: Minimum android version supported for these kits is 19.
3. Add below permissions to manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name= "android.permission.ACCESS_NETWORK_STATE"/>
Development Process
Push Kit
Adding below for receiving the Data Messages:
Below needs to be added to AndroidManifest file under <Application>:
Code:
<service
android:name=".DemoHmsMessageService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
</intent-filter>
</service>
Obtaining Token
Push token is important to identify the application on a device and works a unique identifier.
Client calls the getToken method in HmsInstanceId to obtain the token from the push kit server which is further used by the server to send the Push notifications to the application.
I have created a method to my Main Activity for obtaining the token as below.
Code:
private void getToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Obtain the app ID from the agconnect-service.json file.
String appId = AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
// Set tokenScope to HCM.
String tokenScope = "HCM";
String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, tokenScope);
Log.i(TAG, "get token: " + token);
// Check whether the token is empty.
if(!TextUtils.isEmpty(token)) {
sendRegTokenToServer(token);
}
} catch (ApiException e) {
Log.e(TAG, "get token failed, " + e);
}
}
}.start();
}
// For logs
private void sendRegTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
Receiving Data Messages
To receive the data messages, we need to create a service and override the “onMessageReceived” method as below
Code:
import android.util.Log;
import com.huawei.hms.push.RemoteMessage;
import com.huawei.hms.push.HmsMessageService;
public class DemoHmsMessageService extends HmsMessageService {
private static final String TAG = null;
@Override
public void onMessageReceived(RemoteMessage message) {
Log.i(TAG, "onMessageReceived is called");
// Check whether the message is empty.
if (message == null) {
Log.e(TAG, "Received message entity is null!");
return;
}
// Obtain the message content.
Log.i(TAG, "get Data: " + message.getData()
+ "\n getFrom: " + message.getFrom()
+ "\n getTo: " + message.getTo()
+ "\n getMessageId: " + message.getMessageId()
+ "\n getSendTime: " + message.getSentTime()
+ "\n getDataMap: " + message.getDataOfMap()
+ "\n getMessageType: " + message.getMessageType()
+ "\n getTtl: " + message.getTtl()
+ "\n getToken: " + message.getToken());
Boolean judgeWhetherIn10s = false;
// If the message is not processed within 10 seconds, create a job to process it.
if (judgeWhetherIn10s) {
startWorkManagerJob(message);
} else {
// Process the message within 10 seconds.
processWithin10s(message);
}
}
private void startWorkManagerJob(RemoteMessage message) {
Log.d(TAG, "Start new job processing.");
}
private void processWithin10s(RemoteMessage message) {
Log.d(TAG, "Processing now.");
}}
Let’s send a Data Message to our App Users
In order to send the push notifications to the app users, we need to login to AGC.
Step 1: Choose your project
Step 2:
Goto > Grow > Push Kit
Note: Select data processing location if see the prompt to add one.
Step 3:
Goto > Notifications > Add Notifications
Step 4:
Create a new notification which needs to send to user and fill the below information.
Step 5:
Select Data message and fill the Name and Key-Value pair information.
Step 6:
Click on Test Effect and enter the token.
Click OK.
Step 7:
Scroll down and fill information for Push Scope as Specified device.
Fill Token for the device (Same as above).
Step 8:
Scroll down and fill information for Push time and other parameters.
Click Submit.
Step 9:
Click OK.
Analytics Kit
Initialization
We will be creating instance for the analytics to get the data on the console.
Code:
private Analystics(Context context){
this.context=context;
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(context);
}
public static Analystics getInstance(Context context){
if (analystics==null){
analystics=new Analystics(context);
}
return analystics;
}
Checking the Analytical data on AGC
Login to AGC
Step 1: Choose your project
Step 2:
Goto Huawei Analytics
Results
Goto >> Behaviour analysis >> Page analysis
Tips and Tricks
1. Events and attributes can be customized in Analytics kit.
2. Huawei Push Kit can work well with your own push server. So to create one, refer this.
3. Always integrate the latest version of the SDK.
4. Reports can be exported from AGC.
Conclusion
This article focuses on explaining the usage of Huawei Push kit-data message, with the help of Task Scheduler application and also showcase the analytical data to analyze the user behavior on the application which will further help to improve the user interaction.
References
GitHub
Push Kit
Analytics Kit
Orignal Source
can i send custom push message?
Can we send notification on specified time?