How To Integrate Huawei Account Kit to a Cordova Project? - Huawei Developers

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?

Related

How to Integrate HUAWEI Analytics Kit in Cordova

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

How to Integrate HUAWEI Analytics Kit in Cordova

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

How to Integrate HUAWEI Nearby Plugin to Cordova 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"
}
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.

[Intermediate] Demystifying data messages and Analytics into Task Scheduler application using Huawei Push Kit and Analytics 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"
}
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?

Use Keyring for Sign-in Across Different Apps and Platforms

It's common for an app developer to develop multiple apps across different platforms. However, an issue that arises is that when signing in to different apps or the same app across different platforms on the same device, users usually needs to repeatedly enter their account name and password even if the same account is used, which has a negative impact on user experience.
Keyring provides developers with the ability to share user authentication credentials across different apps and app platforms, thus creating a seamless sign-in experience for users. In this article I will explain how to integrate Keyring and implement cross-platform & cross-app sign-in.
Preparations​
Before integrating the Keyring SDK, you'll need to perform the following preparations:
1. Configure app information in AppGallery Connect.
2. Create an Android Studio project and configure the Maven repository address. If you are using Android Studio, you can integrate the HMS Core SDK via the Maven repository. Before you start developing an app, integrate the HMS Core SDK into your Android Studio project.
3. Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Integrating the Keyring SDK​
After completing the preparations, let's look at how to integrate the Keyring SDK.
1. Open the app-level build.gradle file in the 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"
}
2. Add a build dependency on the Keyring SDK in the dependencies block.
Find the dependencies block in the build.gradle file, add a dependency on the Keyring SDK in the block, and click Sync Now to make Android Studio synchronize the project.
Code:
dependencies{
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation "com.huawei.hms:keyring-credential:6.1.1.302"
}
Scenario Simulated by the Sample Code​
​The sample code provides two sample apps, which are App1 and App2.
App1 simulates the sign-in operation, and calls APIs of Keyring to save the user sign-in credentials. App1 then shares these credentials with App2.
App2 calls APIs of Keyring to query available credentials, and calls the getContent API to obtain the user's sign-in password.
To make the sample code work, we need to create two apps in AppGallery Connect, download the agconnect-services.json files of the two apps, and place the files in the corresponding Android Studio projects of App1 and App2. Refer to "Preparations" for details.
Preparing Information​
We need to collect the information listed below for use later on.
We need to set the sharing relationship in the code for App1 and App2. Therefore, we need to query and record the package names and signing certificate fingerprints of App1 and App2. For details about how to obtain the signing certificate fingerprint, please refer to "Preparations."
Development Practice​
1. Configure App1 to save user credentials using the Keyring SDK.
App1 simulates the app sign-in operation, the sample project has only one activity, that is, MainActivity, in which most code lines are used to implement the sign-in screen and basic sign-in logic. This activity has a member object of the CredentialClient type, which is the operation object for accessing Keyring and is initialized in the onCreate method of the activity.
Code:
mCredentialClient = CredentialManager.getCredentialClient(this);
Then, implement the login method for the onClick method of the Login button.
Code:
private void login(View view) {
if (!checkInput()) {
return;
}
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
// connect server to login.
saveCredential(username, password,
"app2", "com.huawei.hms.keyring.sample.app2",
"XX:XX:XX:XX:XX:XX",
true);
}
At the beginning of the login method, the checkInput method is called to check the validity of the user name and password in the input text boxes. In most cases, the service logic will connect to the background and use the user name and password for sign-in. The sample code does not include the code for implementing this. Here, we assume that the user name and password are correct, and that sign-in is performed successfully in the background.
The next step is to call the saveCredential method to save the credentials. The saveCredential method is a simple method encapsulated to highlight the input parameters. Such input parameters include the user name, password, information related to the sharing target app. It also includes the configuration specifying whether user authentication is required during credential reading.
App2's package name and certificate fingerprint recorded earlier will be used here. When calling the saveCredential method, we need to pass the package name and certificate fingerprint of App2 to the method as parameters.
Code:
private void saveCredential(String username, String password,
String sharedToAppName, String sharedToAppPackage,
String sharedToAppCertHash, boolean userAuth) {
AndroidAppIdentity app2 = new AndroidAppIdentity(sharedToAppName,
sharedToAppPackage, sharedToAppCertHash);
List<AppIdentity> sharedAppList = new ArrayList<>();
sharedAppList.add(app2);
Credential credential = new Credential(username,
CredentialType.PASSWORD, userAuth,
password.getBytes());
credential.setDisplayName("nickname_" + username);
credential.setSharedWith(sharedAppList);
credential.setSyncable(true);
mCredentialClient.saveCredential(credential, new CredentialCallback<Void>() {
@Override
public void onSuccess(Void unused) {showMessage("save credential to Keyring success");}
@Override
public void onFailure(long errorCode, CharSequence description) {
showMessage("save to Keyring failed" + " ====" + errorCode + ":" + description);
}
});
}
In the saveCredential method, we use the package name and certificate fingerprint of App2 to create an app object app2. Then, we place this object in sharedAppList of AppIdentity and use the list as a parameter of the credential object. After that, we create a password-type credential object, and call a series of set methods for this object to set the sharing app list and other configurations of the credentials. Finally, we call the saveCredential method of the Keyring operation object mCredentialClient to save the credentials. We also need to set the callback methods called when credentials are successfully saved or failed to be saved.
We have now saved the credentials in Keyring.
2. Configure App2 to use the Keyring SDK to query and read credentials.
App2 simulates the sign-in operation of another app made by the same developer. App2 can use the Keyring SDK to query credentials saved by itself earlier and credentials shared with it by the specified app, and read the credential content for seamless sign-in. App2 also has only one activity, that is, MainActivity, which simulates the sign-in screen. App2, like App1, also defines a member object mCredentialClient of the CredentialClient type and uses the object as the operation object for accessing Keyring. The operation object is also initialized in the onCreate method of the activity. The queryCredential method is called at the end of the onCreate method to query available credentials.
Now, let's look at how to implement the queryCredential method.
Code:
private void queryCredential() {
final AndroidAppIdentity app1 = new AndroidAppIdentity("app1",
"com.huawei.hms.keyring.sample.app1",
"XX:XX:XX:XX:XX:XX"
);
List<AppIdentity> trustedOwnerList = new ArrayList<>();
trustedOwnerList.add(app1);
mCredentialClient.findCredential(trustedOwnerList, new CredentialCallback<List<Credential>>() {
@Override
public void onSuccess(List<Credential> credentials) {
if (credentials.isEmpty()) {
noAvailableCredential();
} else {
MainActivity.this.setCredentialList(credentials);
}
}
@Override
public void onFailure(long errorCode, CharSequence description) {
noAvailableCredential();
}
private void noAvailableCredential(){showMessage("no shared credential");}
});
}
When preparing for SDK integration earlier, we recorded the package name and certificate fingerprint of App1. Now we use the information in the queryCredential method to create an AndroidAppIdentity object representing App1. Then, place the object in trustedOwnerList of AppIdentity.
Next, we call the findCredential method of the Keyring operation object mCredentialClient and pass trustedOwnerList and the result callback to the method. The findCredential method will query and list credentials that are available to this app. Such credentials include those stored by this app and those shared with this app by other apps specified in trustedOwnerList. In the sample code of App2, the findCredential method will query credentials saved by App2 and credentials shared with App2 by App1.
Available credentials exist if the onSuccess method is called and the credentials parameter is not empty. Then, the setCredentialList method will be called to display the credential list in the RecyclerView component on the app screen.
The choose method in the CredentialHolder class will be called if one of the credentials displayed on the screen is chosen. In the choose method, the selected credential object will be assigned to the member object mChooseCredential. After the user taps the Login button on the app screen, the login method will be called.
Code:
private void login(View v) {
if (mChooseCredential == null) {
showMessage("please_choose_account");
return;
}
mChooseCredential.getContent(new CredentialCallback<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
// String password = new String(bytes);
showMessage("Login success");
}
@Override
public void onFailure(long l, CharSequence charSequence) {
showMessage("Get password failed");
}
});
}
In the login method, if mChooseCredential is not empty, the getContent method of the chosen credential object will be called to obtain the credential content. When calling the getContent method, we also need to pass the result callback to it.
The bytes parameter in the onSuccess method indicates the credential content, that is, the user sign-in password saved by App1. In a real app, we can directly use the password for sign-in, creating a seamless sign-in experience.
That's all for this tutorial. You can visit the Keyring official website for more information.
Does it support for quickApp?
Basavaraj.navi said:
Does it support for quickApp?
Click to expand...
Click to collapse
Yes, it supports quick apps.

Categories

Resources