HMS Core Health Kit provides REST APIs for apps to access its database and for them to provide app users with health and fitness services. As I wanted to implement health functions into my app, I chose to integrate Health Kit. While integrating the kit, I encountered and collected some common issues, as well as their solutions, related to this kit, which are all listed below. I hope you find this helpful.
Connectivity test fails after registering the subscription notification capabilityWhen you test the connectivity of the callback URL after registering as a subscriber, the system displays a message indicating that the connectivity test has failed and the returned status code is not 204.
CauseIf the HTTP status code of the callback URL is not 204, 404 will be returned, indicating that the callback URL connectivity test has failed, even if you can access the URL.
Read Subscribing to Data for reference.
SolutionMake sure that the URL is accessible and the returned status code is 204.
The total number of steps returned by the sampling data statistics API is inconsistent with the value calculated based on the step detailsObtain the total number of steps by calling the API for Querying Sampling Data Statistics.
API URL: https://health-api.cloud.huawei.com/healthkit/v1/sampleSet:polymerize
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000,
"groupByTime": {
"groupPeriod": {
"timeZone": "+0800",
"unit": "day",
"value": 1
}
}
}
As shown below, the total number of steps returned is 7118.
{
"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"
}
Obtain step details by calling the Querying Sampling Data Details API and calculate the total number of steps.
API URL: https://health-api.cloud.huawei.com/healthkit/v1/sampleSet:polymerize
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000
}
As shown below, the total number of steps calculated based on the returned result is 6280.
As we can see, the total number of steps generated in a time segment returned by the sampling data statistics API differs from the value calculated based on the step details.
CauseAs detailed data and statistical data are reported separately, detailed data delay or loss may lead to such inconsistencies.
When you query the data of a day as follows, you will obtain statistical data, rather than the value calculated based on the detailed data.
SolutionWhen querying the total number of steps, pass the groupByTime parameter, and set the duration parameter.
Request parameters:
Code:
{
"polymerizeWith": [
{
"dataTypeName": "com.huawei.continuous.steps.delta"
}
],
"endTime": 1651809600000,
"startTime": 1651766400000,
"groupByTime": {
"duration": 86400000
}
}
As shown below, the returned value is 6280, similar to what you calculated based on the detailed data.
Error code 403 is returned, with the message "Insufficient Permission: Request had insufficient authentication scopes."
CauseError 403 indicates that the request has been rejected. This error occurs when your app does not have sufficient scopes.
Solution1. Check whether you have applied for relevant scopes on the HUAWEI Developers Console.
2. Check whether you have passed the scopes during authorization, and whether users have granted your app these scopes.
The following is an example of passing the step count read scope during authorization.
Make sure that users have selected the relevant scopes when authorizing your app.
Error code 400 is returned, with the message "Insufficient Permission: Request had insufficient authentication scopes."Let us take querying step count details as an example.
Let's say that the request parameters are set as follows:
Access token: generated based on the code of the first authorization.
Time of the first authorization (time when the code is generated for the first time): about 8:00 AM on May 7, 2022.
Time range of data collection:
Start time: 2022-05-06 00:00:00 (1651766400000)
End time: 2022-05-06 12:00:00 (1651809600000)
Request:
Response:
CauseTo protect user data, you are only allowed to read data generated after a user has authorized you to do so. To read historical data generated before a user has granted authorization, you will need to obtain the read historical data scope. If the user does not grant your app this scope, and the start time you set for querying data is earlier than the time you obtained the user's authorization, the start time will revert to the time you first obtained the user's authorization. In this case, error 400 (invalid startTime or endTime) will be reported once the corrected start time is later than the end time you set, or only data generated after the authorization will be available.
In this example, the user does not grant the app the read historical data scope. The start date is May 6, whereas the date when the user authorized the app is May 7. In this case, the start date will be automatically adjusted to May 7, which is later than May 6, the end date. That is why error 400 (invalid startTime or endTime) is returned.
Suggestion1. Check whether you have applied for the read historical data scope on the HUAWEI Developers Console.
Currently, historical data is available by week, month, or year. You can query historical data generated as early as one year before a user's authorization is acquired.
ScopeDescriptionRemarks
https://www.huawei.com/healthkit/historydata.open.week
Reads the previous week's data from Health Kit.Only the previous week's data before the user authorization can be read.
https://www.huawei.com/healthkit/historydata.open.month
Reads the previous month's data from Health Kit.Only the previous month's data before the user authorization can be read.
https://www.huawei.com/healthkit/historydata.open.year
Reads the previous year's data from Health Kit.Only the previous year's data before the user authorization can be read.
2. When generating an authorization code, add the scopes listed in the preceding table, so that users can grant your app the read historical data scope after logging in to their HUAWEI ID.
Data queried after the authorization:
References HMS Core Health Kit
Related
AppsUP contest has been launched since June 30. Many developers meet the following issues in the process. If you also have the same issue which needs to be resolved, these questions in the list will be timely help. Any doubts or questions about Analytics Kit, this post can be a reference.
Q: When I integrate analysis kit, the compilation errors occurs in React Native Version 0.59.8
A: If you are migrating your app to HMS, suggest you to cross reference your original project and simply add the line to the buildscript/repositories and allprojects/repositories blocks.
The details you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201248163576960163&fid=0101187876626530001
Q: Can we change the data storage for Advanced Analytics and How?
A: Till now there is no option to change the Data Storage Location, but you can reset it by deleting your existing app and recreating the app. Then you will see the option to set data storage location option during configuring the developer option. At the same time you must be careful about setting of Data Storage Location because once it set you can't change or modify it.
Q: Huawei analysis shows that the user data does not match the user data displayed on the background of Huawei analysis.
A: According to Huawei analysis, all users are virtual users.
If an application is uninstalled and then reinstalled on a mobile phone, the number of users is counted as two.
Therefore, the number of users calculated by Huawei analysis is greater than or equal to the actual number of users.
Q: If developers need to report some customized user property, which API can be use?
A: You should use "setUserProfile" method of this class: com.huawei.hms.analytics.HiAnalyticsInstance
Attributes will be reported to AGC Analytics and will be usable.
API description is as below:
{
"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"
}
link:
https://developer.huawei.com/consumer/en/doc/development/HMS-References/3021008#setUserProfile
Q: How to export data to an app server through the data export API provided by the Analytics Kit gateway?
A: Before calling Analytics Kit APIs, you need to obtain the token for authentication. This process involves three parameters, wherein: client_id is the app ID obtained during app creation, client_secret is the password for the app ID that can be queried on HUAWEI Developers, grant_type has a fixed value of client_credentials. In the following example, the getToken() method sends a POST request encapsulating the HTTP tool class to obtain the token and convert the obtained token into an object for subsequent authentication.
More details, you can refer:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201302699264940068&fid=0101187876626530001
Q: Integrated Analytics Kit, Why Does the Server Return Error Code 402 When Data Fails to Be Reported?
A: Developers have modified the agconnect-services.json configuration. As a result, the app fails to obtain the AGC token.
Q: Where Is Entry Menu of HUAWEI Analytics Kit?
A: HUAWEI Analytics Kit has been enhanced to provide the cross-platform analysis capabilities, allowing one-stop, unified analysis of Android and iOS users. It looks into the user-centric analysis and helps you understand user behavior on the Android and iOS platforms. For easier access, the entry menu on AppGallery Connect has been changed from Analyze > Advanced analysis (beta) to My projects > HUAWEI Analytics. You can view the overall analysis report or analysis report specific to a certain platform or app in your project. You can even compare user behaviors of different apps and platforms.
Q: Why reporting of custom events fails when I was conducting cross-platform data analysis using User-ID?
A: Event ID definition rule of HUAWEI Analytics Kit: An event ID cannot be left empty or contain spaces. It can consist of a maximum of 256 characters including digits, letters, and underscores (_) but cannot start with a digit. In addition, its value cannot be the same as the ID of an automatically collected event.
Therefore, you can change Purchase Test to Purchase_Test or any other value that complies with the preceding rule.
If you have multiple iOS and Android apps in a project, you can use the filter to view the overall analysis report or detailed report of an app. You can even link users' activity data from different devices by using User-ID to obtain cross-platform analysis data. For details about cross-platform analysis, see:
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/3021001
Q: I have integrated the iOS SDK of HUAWEI Analytics Kit into my app but why no log events are collected when the app is running?
A: When this problem occurs, it is probable that the run log parameters have not been set. You can set the log level to any of the following values: -HALogLevelDebug, -HALogLevelInfo, -HALogLevelWarn, and -HALogLevelError.
For example, to set the log level to -HALogLevelDebug, perform the following steps:
Choose Product > Scheme > Edit Scheme from the Xcode menu.
On the Arguments page, click + to add the -HALogLevelDebug parameter.
After the parameter is added, click Close to save the setting.
Q: What should I do if data reporting fails and the server returns error code 401?
A: Cause Analysis:
Possible causes are as follows:
HUAWEI Analytics Kit has not been enabled.
The obtained agconnect-services.json file is not the original file.
The debug mode has not been successfully enabled.
The Logcat log data on the device is not reported successfully.
Solution:
To correct the fault, perform the following steps:
Check whether HUAWEI Analytics Kit has been enabled and whether it has been turned on (default) in the API management.
Check whether the agconnect-services.json file is the original file without any modification.
Check whether the debug mode is enabled.
Check whether the log data is reported successfully. If the log contains resultCode: 200, the data is reported successfully. Possible causes are as follows:
Case 1: The tools:node parameter is set to "replace" (that is, tools:node="replace"). This causes the app configuration to conflict with AppGallery Connect SDK configurations, and therefore an exception occurs when the AppGallery Connect API is called to obtain the token.
Case 2: The configuration for excluding HUAWEI Analytics Kit from obfuscation is not added before you compile the APK. As a result, an exception occurs during the running of the APK.
Open the obfuscation script file of your project.
Add configurations to exclude HUAWEI Analytics Kit from obfuscation.
Set tools:node to "merge" (that is, tools:node="merge").
Manually write all information in the AndroidManifest.xml file of AppGallery Connect to the AndroidManifest.xml file of your app.
Code:
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.agconnect.**{*;}
-keep interface com.huawei.hms.analytics.type.HAEventType{*;}
-keep interface com.huawei.hms.analytics.type.HAParamType{*;}
Related articles you can refer:
[AppsUP] Frequently Asked Questions About Huawei Account Kit
[AppsUP] Frequently Asked Questions About Huawei Map Kit
[AppsUP] Frequently Asked Questions About Huawei Push Kit
More doubts or questions about Analytics Kit, leave your comment below or ask your questions in HUAWEI Developer Forum.
More information like this, you can visit HUAWEI Developer Forum
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201258006396920241&fid=0101187876626530001
Foreword
The previous articles have introduced the function development of using HMS ML Kit SDK to implement Smile Capture Snapshot, ID photo DIY and photo translation,this time I will introduce to you the use of HMS Machine Learning Service (ML Kit) bank card recognition SDK, quickly bind credit cards.
Application scenarios of bank card recognition
Before introducing the development steps, let ’s talk about the specific application scenarios of bank card recognition,For banking apps, mobile payments app, e-commerce apps, or other apps with payment functions, during the use process, we often encounter the following common application scenarios:
· Card payment
Commonly used in payment apps, or apps with payment functions,used to bind credit cards, UnionPay debit cards, and provide online payment functions
· transfer money
Commonly used in bank or payment apps to transfer funds to users of our bank or other banks.
· Real-name authentication, identity verification
For example, social APP,Complete quick real-name authentication through the identity information associated with the bank card.
Whether it is card tying, money transfer or identity verification,will encounter a critical step,enter bank card information,such as bank card number, validity period, etc.;Since bank card numbers tend to be longer,manual entry is very error-prone,poor user experience;With the help of the HMS ML Kit bank card specific recognition capability,Can easily deal with the above scenarios, quickly and accurately enter bank card information, improve user experience.
How to use Huawei bank card identification service
Bank card recognition service can input bank card information through video streaming,obtain the important text information such as the card number and expiration date of the bank card in the 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"
}
Bank card identification provides processing plug-ins. Developers can integrate a bank card recognition plug-in without the need to process camera video stream data, thereby achieving rapid integration of bank card recognition capabilities.
Key process of integrated bank card identification service
Since Huawei provides a bank card identification plug-in, developers can directly call the bank card plug-in, so the development steps are simpler, and only need to pull up the interface to obtain the result to complete the identification of the card number.
publishing ur app on Huawei AppGallery can refer to:https://forums.developer.huawei.com...d=0201253492001500241&fid=0101187876626530001
Development steps
1 Development preparation
1.1 Add Huawei maven address in project-level gradle
Code:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
} }allprojects {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}}
1.2 Add SDK dependencies to the application-level build.gradle
Code:
dependencies{
// Introduce the basic SDK,please use the newest version according to the development
implementation 'com.huawei.hms:ml-computer-vision-bcr:1.0.3.303'
// Introduce bank card identification plugin package ,please use the newest version according to the development
implementation 'com.huawei.hms:ml-computer-card-bcr-plugin:1.0.3.300'
// Introduce bank card recognition model package ,please use the newest version according to the development
implementation 'com.huawei.hms:ml-computer-card-bcr-model:1.0.3.300' }
1.3Automatically download the incremental incremental model in the AndroidManifest.xml file
To enable the application to automatically update the latest machine learning model to the user device after the user installs your application from the Huawei application market, add the following statement to the AndroidManifest.xml file of the application:
Code:
<manifest
...
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value= "bcr"/>
<!--If multiple models are required,set the parameter as follows:
android:value="object,ocr,face,label,icr,bcr,imgseg"-->
... </manifest>
1.4 Apply for camera and storage permissions in the AndroidManifest.xml file
Code:
<!--Camera permissions--> <uses-permission android:name="android.permission.CAMERA" />
<!--Use storage permissions--><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2 Key steps in code development
2.1 Create a recognition result callback function
Overload onSuccess, onCanceled, onFailure, onDenied four methods; onSuccess means recognition success, MLBcrCaptureResult is recognition return result, onCanceled means user cancel, onFailure means recognition failure, onDenied means camera is unavailable
Code:
private MLBcrCapture.Callback callback = new MLBcrCapture.Callback() {
@Override
public void onSuccess(MLBcrCaptureResult bankCardResult){
// Identify successful processing。
}
@Override
public void onCanceled(){
// User cancel processing
}
// Callback method where no text information can be recognized or a system exception occurs during the recognition process。
// retCode:error code。
// bitmap:Card picture of failed test
@Override
public void onFailure(int retCode, Bitmap bitmap){
// Identify exception handling。
}
@Override
public void onDenied(){
// The camera does not support such scene processing。
} };
2.2 Set the identification parameters, call the captureFrame interface of the recognizer for recognition, and the recognition result will be returned through the callback function in step 2.1
Code:
private void startCaptureActivity(MLBcrCapture.Callback callback) {
MLBcrCaptureConfig config = new MLBcrCaptureConfig.Factory()
// Set the identification interface horizontal and vertical screen, support three modes:
// MLBcrCaptureConfig.ORIENTATION_AUTO: Adaptive mode, the physical sensor determines the display direction。
// MLBcrCaptureConfig.ORIENTATION_LANDSCAPE: Landscape mode。
// MLBcrCaptureConfig.ORIENTATION_PORTRAIT: Portrait mode。
.setOrientation(MLBcrCaptureConfig.ORIENTATION_AUTO)
.create();
MLBcrCapture bankCapture = MLBcrCaptureFactory.getInstance().getBcrCapture(config);
bankCapture.captureFrame(this, callback); }
2.3 In the callback of the detection button, the method defined in step 2.2 is called to realize bank card recognition
Code:
@Override
public void onClick(View v) {
switch (v.getId()) {
// detect button
case R.id.detect:
startCaptureActivity(callback);
break;
default:
break;
} }
Demo effect
github source
The source code has been uploaded to github, you can also improve this function together on github。
github source address:https://github.com/HMS-Core/hms-ml-demo
Bank card identification demo code path:MLKit-Sample\module-text\src\main\java\com\mlkit\sample\activity\BankCardRecognitionActivity.java
For more detailed development guide, refer to the official website of Huawei Developer
Now you have a quick app released on HUAWEI AppGallery. Do you want to attract more users and win more traffic for it? HUAWEI Push Kit can help you with that. You can push messages at the right moment to users for them to open your quick app to view more details. This better engages your users and improves activity.
Typical scenarios of push messages are as follows:
l Shopping quick apps can push information about new products and discounts to users to attract more customers for merchants.
l Reading quick apps can push information such as popular books and chapter updates to users, providing up-to-date information that users concern about.
l Food & drink quick apps can push information about food and good restaurants to users, facilitating user's life and bringing more users for the catering industry.
Follow instructions in this document to integrate HUAWEI Push Kit to your quick app to get all these benefits.
Getting Started
The hardware requirements are as follows:
l A computer with Node.js 10 or later and HUAWEI Quick App IDE of the latest version installed
l A Huawei mobile phone running EMUI 8.0 or later (with a USB cable)
Development Guide
Enabling HUAWEI Push Kit
1. Sign in to AppGallery Connect and click My projects.
2. Click the card of the project for which you need to enable the service. Click the Manage APIs tab, and toggle the Push Kit switch.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Click the General information tab. In the App information area, set SHA-256 certificate fingerprint to the SHA-256 fingerprint.
Subscribing to Push Messages
The service process is as follows.
1. Call the push.getProvider API to check whether the current device supports HUAWEI Push Kit. If huawei is returned, the device supports HUAWEI Push Kit. You can call other relevant APIs only when the device supports HUAWEI Push Kit.
2. Call the push.subscribe API to obtain regId (registered ID). The ID is also called a token or push token, which identifies messages sent by HUAWEI Push Kit.
Notice: It is recommended that the preceding APIs be called in app.ux that takes effect globally.
Code:
checkPushIsSupported(){
let provider= push.getProvider();
console.log("checkPush provider= "+provider);
if(provider==='huawei'){
this.pushsubscribe();
}
},
pushsubscribe() {
console.log("pushsubscribe start");
var that=this;
push.subscribe({
success: function (data) {
console.log("push.subscribe succeeded, result data=" + JSON.stringify(data));
that.dataApp.pushtoken=data.regId;
},
fail: function (data, code) {
console.log("push.subscribe failed, result data=" + JSON.stringify(data) + ", code=" + code);
},
complete: function () {
console.log("push.subscribe completed");
}
})
},
3. Report the obtained regId to the server of your quick app through the Fetch Data API, so the server can push messages to the device based on regId. Generally, the value of regId does not change and does not need to be reported to the server each time after it is obtained.
You are advised to call the Data Storage API to store the regId locally. Each time the regId is obtained, compare the regId with that stored locally. If they are the same, the regId does not need to be reported to the server. Otherwise, report the regId to the server.
The service process is as follows.
The sample code for comparing the obtained regId with that stored locally is as follows:
Code:
checkToken() {
var subscribeToken=this.$app.$def.dataApp.pushtoken;
console.log("checkToken subscribeToken= "+subscribeToken);
var storage = require("@system.storage");
var that=this;
storage.get({
key: 'token',
success: function (data) {
console.log("checkToken handling success data= "+data);
if (subscribeToken != data) {
// Report regId to your service server.
that.uploadToken(subscribeToken);
that.saveToken(subscribeToken);
}
},
fail: function (data, code) {
console.log("handling fail, code = " + code);
}
})
},
The sample code for saving regId locally is as follows:
Code:
saveToken(subscribeToken){
console.log("saveToken");
var storage = require("@system.storage");
storage.set({
key: 'token',
value: subscribeToken,
success: function (data) {
console.log("saveToken handling success");
},
fail: function (data, code) {
console.log("saveToken handling fail, code = " + code);
}
})
},
Testing Push Message Sending
You can test the push function by sending a push message to your test device. In this case, regId (push token) uniquely identifies your device. With it, your service server can accurately identify your device and push the message to your quick app on the device. Your device can receive the pushed message in any of the following conditions:
l The quick app has been added to the home screen.
l The quick app has been added to MY QUICK APP.
l The quick app has been used before.
l The quick app is running.
You can use either of the following methods to send a push message to a quick app that has been released on AppGallery or run by Huawei Quick App Loader.
l Select some target users in AppGallery Connect and send the push message.
l Call the specific server API to send the push message to users in batches.
Sending a Push Message Through AppGallery Connect
This method is simple. You only need to configure the recipients in AppGallery Connect. However, the target user scope is smaller than that through the API.
1. Sign in to AppGallery Connect and click My apps.
2. Find your app from the list and click the version that you want to test.
3. Go to Operate > Promotion > Push Kit. Click Add notification and configure the push message to be sent.
Sending a Push Message by Calling the API
1. Call the accessToken API to obtain the access token, which will be used in the push message sending API.
2. Call the push message sending API. The sample code of the push message body is as follows:
Code:
var mData = {
"pushtype": 0, // The value 0 indicates a notification message.
"pushbody": {
"title": "How can young people make a living? ",
"description": "Why did he choose to be a security guard after college graduation? ",
"page": "/", // Path of the quick app page that is displayed when a user taps a notification message. This parameter is valid only when pushtype is set to 0. /" Go to the app home page.
"params": {
"key1": "test1",
"key2": "test2"
},
"ringtone": {
"vibration": "true",
"breathLight": "true"
}
}
};
var formatJsonString = JSON.stringify(mData);
var messbody = {
"validate_only": false,
"message": {
"data": formatJsonString, // The data type is JsonString, not a JSON object.
"android": {
"fast_app_target": 1, // The value 1 indicates that a push message is sent to a quick app running by Huawei Quick App Loader. To send a push message to a quick app from AppGallery, set this parameter to 2.
"collapse_key": -1,
"delivery_priority": "HIGH",
"ttl": "1448s",
"bi_tag": "Trump",
},
"token": ['pushtoken1','pushtoken2'], // Target users of message pushing.
}
};
For details, please refer to Accessing HUAWEI Push Kit.
How much time it will take to integrate push kit into Quick App ?
1. Background
Cordova is an open-source cross-platform development framework that allows you to use HTML and JavaScript to develop apps across multiple platforms, such as Android and iOS. So how exactly does Cordova enable apps to run on different platforms and implement the functions? The abundant plugins in Cordova are the main reason, and free you to focus solely on app functions, without having to interact with the APIs at the OS level.
HMS Core provides a set of Cordova-related plugins, which enable you to integrate kits with greater ease and efficiency.
2. Introduction
Here, I'll use the Cordova plugin in HUAWEI Push Kit as an example to demonstrate how to call Java APIs in JavaScript through JavaScript-Java messaging.
The following implementation principles can be applied to all other kits, except for Map Kit and Ads Kit (which will be detailed later), and help you master troubleshooting solutions.
3. Basic Structure of Cordova
When you call loadUrl in MainActivity, CordovaWebView will be initialized and Cordova starts up. In this case, CordovaWebView will create PluginManager, NativeToJsMessageQueue, as well as ExposedJsApi of JavascriptInterface. ExposedJsApi and NativeToJsMessageQueue will play a role in the subsequent communication.
During the plugin loading, all plugins in the configuration file will be read when the PluginManager object is created, and plugin mappings will be created. When the plugin is called for the first time, instantiation is conducted and related functions are executed.
A message can be returned from Java to JavaScript in synchronous or asynchronous mode. In Cordova, set async in the method to distinguish the two modes.
In synchronous mode, Cordova obtains data from the header of the NativeToJsMessageQueue queue, finds the message request based on callbackID, and returns the data to the success method of the request.
In asynchronous mode, Cordova calls the loop method to continuously obtain data from the NativeToJsMessageQueue queue, finds the message request, and returns the data to the success method of the request.
In the Cordova plugin of Push Kit, the synchronization mode is used.
4. Plugin CallYou may still be unclear on how the process works, based on the description above, so I've provided the following procedure:
1. Install the plugin.
Run the cordova plugin add u/hmscore/cordova-plugin-hms-push command to install the latest plugin. After the command is executed, the plugin information is added to the plugins directory.
{
"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 plugin.xml file records all information to be used, such as JavaScript and Android classes. During the plugin initialization, the classes will be loaded to Cordova. If a method or API is not configured in the file, it is unable to be used.
2. Create a message mapping.
The plugin provides the methods for creating mappings for the following messages:
1) HmsMessaging
In the HmsPush.js file, call the runHmsMessaging API in asynchronous mode to transfer the message to the Android platform. The Android platform returns the result through Promise.
The message will be transferred to the HmsPushMessaging class. The execute method in HmsPushMessaging can transfer the message to a method for processing based on the action type in the message.
Code:
public void execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { hmsLogger.startMethodExecutionTimer(action); switch (action) { case "isAutoInitEnabled": isAutoInitEnabled(callbackContext); break; case "setAutoInitEnabled": setAutoInitEnabled(args.getBoolean(1), callbackContext); break; case "turnOffPush": turnOffPush(callbackContext); break; case "turnOnPush": turnOnPush(callbackContext); break; case "subscribe": subscribe(args.getString(1), callbackContext); break;
The processing method returns the result to JavaScript. The result will be written to the nativeToJsMessageQueue queue.
Code:
callBack.sendPluginResult(new PluginResult(PluginResult.Status.OK,autoInit));
2) HmsInstanceId
In the HmsPush.js file, call the runHmsInstance API in asynchronous mode to transfer the message to the Android platform. The Android platform returns the result through Promise.
The message will be transferred to the HmsPushInstanceId class. The execute method in HmsPushInstanceId can transfer the message to a method for processing based on the action type in the message.
Code:
public void execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (!action.equals("init")) hmsLogger.startMethodExecutionTimer(action);
switch (action) { case "init": Log.i("HMSPush", "HMSPush initialized "); break; case "enableLogger": enableLogger(callbackContext); break; case "disableLogger": disableLogger(callbackContext); break; case "getToken": getToken(args.length() > 1 ? args.getString(1) : Core.HCM, callbackContext); break; case "getAAID": getAAID(callbackContext); break; case "getCreationTime": getCreationTime(callbackContext); break;
Similarly, the processing method returns the result to JavaScript. The result will be written to the nativeToJsMessageQueue queue.
Code:
callBack.sendPluginResult(new PluginResult(PluginResult.Status.OK,autoInit));
This process is similar to that for HmsPushMessaging. The main difference is that HmsInstanceId is used for HmsPushInstanceId-related APIs, and HmsMessaging is used for HmsPushMessaging-related APIs.
3) localNotification
In the HmsLocalNotification.js file, call the run API in asynchronous mode to transfer the message to the Android platform. The Android platform returns the result through Promise.
The message will be transferred to the HmsLocalNotification class. The execute method in HmsLocalNotification can transfer the message to a method for processing based on the action type in the message.
Code:
public void execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { switch (action) { case "localNotification": localNotification(args, callbackContext); break; case "localNotificationSchedule": localNotificationSchedule(args.getJSONObject(1), callbackContext); break; case "cancelAllNotifications": cancelAllNotifications(callbackContext); break; case "cancelNotifications": cancelNotifications(callbackContext); break; case "cancelScheduledNotifications": cancelScheduledNotifications(callbackContext); break; case "cancelNotificationsWithId": cancelNotificationsWithId(args.getJSONArray(1), callbackContext); break;
Call sendPluginResult to return the result. However, for localNotification, the result will be returned after the notification is sent.
3. Perform message push event callback.
In addition to the method calling, message push involves listening for many events, for example, receiving common messages, data messages, and tokens.
The callback process starts from Android.
In Android, the callback method is defined in HmsPushMessageService.java.
Based on the SDK requirements, you can opt to redefine certain callback methods, such as onMessageReceived, onDeletedMessages, and onNewToken.
When an event is triggered, an event notification is sent to JavaScript.
Code:
public static void runJS(final CordovaPlugin plugin, final String jsCode) { if (plugin == null) return; Log.d(TAG, "runJS()");
plugin.cordova.getActivity().runOnUiThread(() -> { CordovaWebViewEngine engine = plugin.webView.getEngine(); if (engine == null) { plugin.webView.loadUrl("javascript:" + jsCode);
} else { engine.evaluateJavascript(jsCode, (result) -> {
}); } }); }
Each event is defined and registered in HmsPushEvent.js.
exports.REMOTE_DATA_MESSAGE_RECEIVED = "REMOTE_DATA_MESSAGE_RECEIVED"; exports.TOKEN_RECEIVED_EVENT = "TOKEN_RECEIVED_EVENT"; exports.ON_TOKEN_ERROR_EVENT = "ON_TOKEN_ERROR_EVENT"; exports.NOTIFICATION_OPENED_EVENT = "NOTIFICATION_OPENED_EVENT"; exports.LOCAL_NOTIFICATION_ACTION_EVENT = "LOCAL_NOTIFICATION_ACTION_EVENT"; exports.ON_PUSH_MESSAGE_SENT = "ON_PUSH_MESSAGE_SENT"; exports.ON_PUSH_MESSAGE_SENT_ERROR = "ON_PUSH_MESSAGE_SENT_ERROR"; exports.ON_PUSH_MESSAGE_SENT_DELIVERED = "ON_PUSH_MESSAGE_SENT_DELIVERED";
Java:
function onPushMessageSentDelivered(result) { window.registerHMSEvent(exports.ON_PUSH_MESSAGE_SENT_DELIVERED, result); } exports.onPushMessageSentDelivered = onPushMessageSentDelivered;
Please note that the event initialization needs to be performed during app development. Otherwise, the event listening will fail. For more details, please refer to eventListeners.js in the demo.
If the callback has been triggered in Java, but is not received in JavaScript, check whether the event initialization is performed.
In doing so, when an event is triggered in Android, JavaScript will be able to receive and process the message. You can also refer to this process to add an event.
5. Summary
The description above illustrates how the plugin implements the JavaScript-Java communications. The methods of most kits can be called in a similar manner. However, Map Kit, Ads Kit, and other kits that need to display images or videos (such as maps and native ads) require a different method, which will be introduced in a later article.
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source
Account Kit provides simple, secure, and quick sign-in and authorization functions. Rather than having users enter accounts and passwords and wait for authentication, you can let your users simply tap Sign in with HUAWEI ID to quickly and securely sign in to an app with their HUAWEI IDs.
And this is the very reason why I integrated this kit into my app. While doing so, I encountered and collated some common issues related to this kit, as well as their solutions, which are all listed below. I hope you find this helpful.
1. What is redirect_url and how to configure it?redirect_url, or redirection URL, is not the real URL of a specific webpage. Its value is a character string starting with https://. Although it can be customized to whatever you want, you are advised to assign a meaningful value to this parameter according to your service's features.
According to OAuth 2.0, in a web app, redirect_url works in the following scenario: After obtaining user authorization from the OAuth server, the web app will jump to the redirection URL. The web app needs to obtain the authorization code through the URL. To obtain an access token, pass the URL as a parameter to the request that will be sent to the OAuth server. Then, the server will check whether the URL matches the authorization code. If so, the server will return an access token, but if it doesn't, it will return an error code instead.
Check out the instructions in Account Kit's documentation to learn how to set a redirection URL.
2. What's the difference between OpenID and UnionID?An OpenID uniquely identifies a user in an app, but it differs for the same user in different apps.
A UnionID uniquely identifies a user across all apps created under the same developer account.
Specifically speaking, after a user uses their HUAWEI ID to sign in to your apps that have integrated Account Kit, the apps will obtain the OpenIDs and UnionIDs of that user. The OpenIDs are different, but the UnionIDs are the same. In other words, if you adopt the OpenID to identify users of your apps, a single user will be identified as different users across your apps. However, the UnionID for a single user does not change. Therefore, if you want to uniquely identify a user across your apps, the UnionID is advised. Note that if you transfer one of your apps from one developer account to another, the UnionID will also change.
3. How do I know whether an account has been used to sign in to an app?To know this, you can call the style='mso-bidi-font-weight:normal'>silentSignIn API. If the value of the returned style='mso-bidi-font-weight:normal'>authAccount object in style='mso-bidi-font-weight:normal'>onSuccess is not null, this indicates that the account has been used to sign in to an app.
Code:
Task<AuthAccount> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
if(null != authAccount) {
showLog("success ");
}
}
});
4. What to do when error invalid session is reported after the user.getTokenInfo API is called?1. Check whether all input parameters are valid.
2. Confirm that the access_token parameter in the request body has been converted through URL encoding before it is added to the request. Otherwise, if the parameter contains special characters, invalid session will be reported during parameter parsing.
{
"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"
}
Click here to know more details about this API.
5. Is redirect_uri a mandatory parameter in the API for obtaining an access token?Whether this parameter is mandatory depends on the usage scenarios of the API. Specifically speaking:
The parameter is mandatory, when the API is called to obtain the access token, refresh token, and ID token through the authorization code that has been obtained.
The parameter is not mandatory when a refresh token is used to obtain a new access token.
Check out the official instructions for this API to learn more.
6. How long is the validity of an authorization code, an access token, and a refresh token?Authorization code: valid for 5 minutes. This code can be used only once.
Access token: valid for 1 hour.
Refresh token: valid for 180 days.
7. Common result codes and their solutions907135700This code indicates a failure to call the gateway to query scopes of the app.
To solve it, try the following solutions:
1. Check whether the device can connect to the Internet as normal. If not, this could be because the network connection is unavailable and the network connection does not allow for accessing the site for downloading scopes, due to reasons such as firewall restriction.
2. Check whether the app has been created in AppGallery Connect.
3. Check whether the system time of the device is set to the current time. If not, the device SSL certificate will expire, which will prevent the scopes from being downloaded.
907135701This code indicates that scopes are not configured on OpenGW, which may be due to the insufficient application of services for the app and inconsistent environment settings.
To solve this error, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Check whether the app ID in agconnect-services.json is the same as the app ID in AppGallery Connect.
3. Check whether agconnect-services.json is placed under the app directory, as shown in the following figure.
4. Check whether the environments set for your app and HMS Core (APK) are the same, for example, whether they are all the live-network environment or testing environment.
907135702This code indicates that no certificate fingerprint is configured on OpenGW. To solve this, try the following solutions:
1. Verify that the app has been created in AppGallery Connect.
2. Verify that the SHA-256 certificate fingerprint has been configured in AppGallery Connect. Click here to learn how.
6003This code indicates certificate fingerprint verification failed.
Verify that the certificate fingerprint in your app's APK file is consistent with that configured in AppGallery Connect, by following the steps below:
1. Open the APK file of your app, extract the META-INF directory from the file, obtain the CERT.RSA file in the directory, and run the keytool -printcert -file META-INF/CERT.RSA command to get the signing certificate information.
2. Sign in to AppGallery Connect, click My projects, and select the project you want to check. On the displayed page, select the app, go to Project settings > General information, and check whether the value in SHA-256 certificate fingerprint is the same as that in the previous step.
Click here to learn more about certificate fingerprint configuration.
ReferencesHMS Core Account Kit Overview
HMS Core Account Kit Development Guide