Implementing Message Push for Your Quick App Rapidly - Huawei Developers

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 ?

Related

Recipe To Integrate In-App Messaging In 10 Minutes

This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
{
"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"
}
HMS In-App Messaging is a tool to send relevant messages to target users actively using our app to encourage them to use key app functions. For example, we can send in-app messages to encourage users to subscribe to certain products, provide tips on passing a game level, or recommend activities of a restaurant.
In-App Messaging also allow us to customize our messages, the way it will be sent and also define events for triggering message sending to our users at the right moment.
Today I am going to server you a recipe to integrate In-App Messaging in your apps within 10 minutes.
Key Ingredients Needed
· 1 Android App Project, which supports Android 4.2 and later version.
· 1 SHA Key
· 1 Huawei Developer Account
· 1 Huawei phone with HMS 4.0.0.300 or later
Preparation Needed
· First we need to create an app or project in the Huawei app gallery connect.
· Provide the SHA Key and App Package name of the android project in App Information Section.
· Provide storage location in convention section under project setting.
· Enable App Messaging setting in Manage APIs section.
· After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the json file in the app folder of the android project.
· Copy and paste the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file)
Code:
maven { url 'http://developer.huawei.com/repo/' }
· Copy and paste the below class path inside the dependency section of project build.gradle file.
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
· Copy and paste the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
· Copy and paste below library in the app build.gradle file dependencies section
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.3.1.300'
· Put the below permission in AndroidManifest file.
  a) android.permission.INTERNET
  b) android.permission.ACCESS_NETWORK_STATE
· Now Sync the gradle.
Android Code
1. First we need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
2. Add following code in your project to obtain AAID:
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
3. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
4. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
5. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
6. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Till now we added libraries, wrote the code in android studio using java etc. in the heated pan and the result will look like this:
Code:
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private AGConnectAppMessaging appMessaging;
private HiAnalyticsInstance instance;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(this);
instance.setAnalyticsEnabled(true);
instance.regHmsSvcEvent();
inAppMessaging();
}
private void inAppMessaging() {
appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
}
App Gallery Connect
Before we start using one of our key ingredients i.e. Huawei App Gallery Connect using Huawei Developer Account to serve In-App Messages, I would like to inform you that we can server the main dish into three different flavour or types:
A. Pop-up Message Flavour
B. Banner Message Flavour
C. An Image Message Flavour
In-App Message Using Pop-up Flavour
Let’s serve the main dish using Pop-up Message Flavour.
Step 1: Go to Huawei App Gallery Connect
Step 2: Select My projects.
Step 3: After selecting my projects, select the project which we have create earlier. It will look like this:
Step 4: After selecting the project, we will select App Messaging from the menu. It will look like this:
Step 5: Select New button to create new In-App Message to send to the device.
Step 6: Provide the Name and Description. It will look like this:
Step 7: In the Set style and content section, we have to select the type (which is Pop-up), provide a title, a message body, and choose colour for title text, body text and the background of the message. It will look like this:
Step 8: After providing the details in set style and content section, we will move on to the Image section. We will provide two image here for portrait and landscape mode of the app. Remember for portrait the image aspect ratio should be 3:2 (300x200) and for landscape the image aspect ratio should be either 1:1 (100x100) or 3:2 (300x200). It will look like this:
https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/647/156/2640091000001647156.20200512212645.95630192255042904397797509198276:50510525101557:2800:FA1CFD7E5EA43100725399BB4787A4B9FB44B8E02776FF83D09816D732E0AA63.png​
Step 9: We can also provide a button in the Pop-up message using Button Section. The button contains an action. This Action contains two option. We can provide user with Disable Message action or redirect user to particular URL. The section will look like this:
Step 10: We will now move to the next section i.e Select Sending Target section. Here we can click New condition to add a condition for matching target users. Condition types include app version, OS version, language, country/region, audience, user attributes, last interaction, and initial startup.
Note: In this article, we didn’t used any condition. But you are free to use any condition to send targeted In-App Messages.
The section will look like this:
Step 11: The next section is the Set Sending Time section.
a) We can schedule a date and time to send message.
b) We can also provide an End date and time to stop sending message.
c) We can also display message on an events by using trigger event functionality. For example, we can display a discount of an item in a shopping app. A trigger event is required for each in-app message.
d) Also we can flexibly set the frequency for displaying the message.
This is how it will look:
Step 12: The last section is the Set Conversion Event section. As off now we will keep it as none. It will look like this:
Step 13: Click Save in the upper right corner to complete message creation. Also we can click Preview to preview the display effect of your message on a mobile phone or tablet.
Note: Do not hit the publish button yet. Just save it.
Step 14: In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. To that we need to find the message that you need to test, and click Test in the Operation column as it is shown below:
Step 15: Click Add test user and enter the AAID of the test device in the text box. Also run the app in order to find AAID of the test device in the logcat of the Android Studio.
Step 16: Finally we will publish the message. We will select publish in the operation column. It will look like this:
The Dish

Integrating HUAWEI In-app message with Google In-app message in single Application

More information like this, you can visit HUAWEI Developer Forum​
Introduction
In-App Messaging helps you engage your app's active users by sending targeted, contextual messages that encourage to use key app features. For example, you could send an in-app message to get users to subscribe, watch a video, complete a level, or buy an item. You can customize messages as cards, banners, modals, or images, and set up triggers so that they appear exactly when benefit your users most.
Usecase
1. Add following image on Huawei App gallery connect console and google firebase console to be shown as in-app message in our app.
{
"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. App installed on Huawei device will fetch in-app message (image) from Huawei App gallery connect.
3. App installed on GMS devices will fetch in-app message (image) from Google firebase console.
Huawei In-App Messaging
Prerequisite
1. You must have Huawei developer account.
2. Huawei phone with HMS 4.0.0.300 or later
3. Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Setup:
1. Create a project in android studio.
2. Get the SHA-256 Key.
3. Create an app in the Huawei app gallery connect.
4. Enable account kit setting in Manage APIs section.
5. Provide the SHA-256 Key in App Information Section.
6. Provide storage location.
7. After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in   the app folder of the android project.
8. Enter the below maven url inside the repositories of buildscript and allprojects respectively (project build.gradle file )
Code:
maven { url 'http://developer.huawei.com/repo/' }
9. Enter the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
10. Put the below permission in AndroidManifest file.
  a) android.permission.INTERNET
  b) android.permission.ACCESS_NETWORK_STATE
11. Now Sync the gradle.
Implemetation
1. We need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
2. Add following code in your project to obtain AAID
Code:
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(new OnSuccessListener<AAIDResult>() {
@Override
public void onSuccess(AAIDResult aaidResult) {
String aaid = aaidResult.getId();
Log.d(TAG, "getAAID success:" + aaid );
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "getAAID failure:" + e);
}
});
3. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
4. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
5. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
6. To specify that the in-app message data must be obtained from the AppGallery Connect server by force we will use.
Code:
appMessaging.setForceFetch();
Since we are using a test device to demonstrate the use of In-App Messaging, so we use setForceFetch API. The setForceFetch API can be used only for message testing. Also In-app messages can only be displayed to users who have installed our officially released app version.
Creating Image In-App Messaging on App Gallery connect
1. Sign in to AppGallery Connect and select My projects.
2. Select your project from the project list.
3. Navigate Growing > App Messaging and click New.
4. Set Name and Description for your in-app message.
5. Provide the in-app message Type. For image in-app message, select type as Image.
6. Provide image URL.
7. Provide the action for image tapping.
8. Click next to move on to the next section, that is, Select Sending Target section. Here we can define Condition for matching target users. In this article, we did not use any condition.
9. The next section is the Set Sending Time section.
We can schedule a date and time to send in-app message.
We can also provide an End date and time to stop sending message.
We can also display message on an events by using trigger event functionality. For example, we can display a discount of an item in a shopping app. A trigger event is required for each in-app message.
Also we can flexibly set the frequency for displaying the in-app message.
10. Click Next, find Set conversation events. It associates the display or tap of the app message with a conversion event. The conversion relationship will be displayed in statistics. As off now we will keep it as none.
11. Click Save in the upper right corner to complete message creation.
12. In-app messages can only be displayed to users who have installed our officially released app version. App Messaging allows us to test an in-app message when our app is still under tests. Find the message that you need to test, and click Test in the Operation column as shown below:
13. Provide the AAID of the test device in the text box. Click Save.
14. Click Publish.
Google firebase In-App Messaging
Steps:
1. To enable Firebase in your app, add following lines in your root-level build.gradle file.
Code:
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
// ...
// Add the following line:
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
}
}
allprojects {
// ...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
// ...
}
}
2. In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin:
Code:
apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}
3. To your module (app-level) Gradle file (usually app/build.gradle), add the dependencies.
Code:
dependencies {
// Add the Firebase SDK for Google Analytics
implementation 'com.google.firebase:firebase-analytics:17.4.4'
implementation 'com.google.firebase:firebase-auth:19.3.2'
}
4. That testing device is determined by a FirebaseInstallations ID, or FID. Find your testing app's FID by checking the Logcat in Android Studio for the following `Info` level log:
Code:
I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID YOUR_INSTALLATION_ID
We will add this FID while composing in-app message on firebase console.
5. Set up your new campaign in the Firebase consoles Firebase In-App Messaging page.
6. Select your project and click Create a new campaign.
7. In this article, we will use image in-app message. Select message layout as Image only. Provide Image URL and click Next.
8. Provide campaign name and description and define your target user. Here we have not defined any target user.
9. Click Next to define campaign start time, end time, trigger event and frequency limit of in-app message.
10. Click Next and provide conditional events and additional options. These are optional. Click Save as draft.
11. Select Test on Device, and add the earlier generated FID.
12. Run the application on GMS installed device, you will see Google in-app message.
To check if device has HMS or GMS installed
Code:
public class Utils {
public static boolean isSignedIn = false;
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}
public static boolean isDeviceHuaweiManufacturer () {
String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;
}
}
References:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-appmessage-introduction
https://firebase.google.com/docs/in-app-messaging/get-started?platform=android

Exploring the Huawei Health Kit: Data Controller

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201326975480310022&fid=0101246461018590361
Hello everyone , in this article we’re going to take a look at the Huawei Health Kit features so we can easily put these features to our apps.
Health app industry have shown an important increase in recent years.The software and healthcare industry are working together to find the latest technology products for the needs of patients and families.Huawei offers high technology service for the health and fitness app ecosystem with HealthKit and HiHealthKit service.Huawei and third-party partner capabilities track and customize all aspects of better living.
Data storage : Provides a platform for users to store their fitness and health data.
Data openness : Provides a wide range of APIs for writing and reading speed, positioning, blood sugar level, and other data.
Data interaction : Enables you and your users to agree on data access, guaranteeing proper use and security of personal data.
HealthKit:
https://developer.huawei.com/consumer/en/hms/huawei-healthkit
HiHealth:
https://developer.huawei.com/consumer/en/hms/huawei-healthkit
We will examine the differences between HealthKit and HiHealth in our next articles.I created a sample app which I’ve open-sourced on GitHub for enthusiasts who want to use this service.
https://github.com/tualdev/hms-health-kit-demo
Setting up the Health Kit
You’ll need to do setup before you can use the Health Kit.You can follow the official documentation on how to prepare app and enable Health Kit on App Gallery Connect.
Also you can follow this blog post to integrate your apps with Huawei HMS Core:
https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98
I’ll show you how to implement Data Controller features in this article for your android projects.Let’s get started!
Add the required dependencies to the build.gradle file under app folder.We need some dependencies.
Code:
implementation 'com.huawei.hms:hwid:4.0.1.300'
implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.3.1.300'
implementation 'com.huawei.hms:hihealth-base:5.0.0.300'
Add the required permissions to the AndroidManifest.xml file under app/src/main folder.
Code:
<uses-permission android:name="android.permission.INTERNET" />
You need to give some permissions after applying for HealthKit in service cards area.The applied permissions will be displayed on the user authorization page.
{
"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"
}
Let’s continue by coding Data Controller functionalities in our project.
Sign-in before using Data Controller
Firstly, we need to configure Huawei ID sign in.After that, we will start sign intent while using startActivityForResult method.We added also some scopes to apply for. The following only shows an example. You need to add scopes according to your specific needs.
Code:
huaweiIdAuthParamsHelper = HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
val scopeList = listOf(
Scope(HwIDConstant.SCOPE.SCOPE_ACCOUNT_EMAIL),
Scope(HwIDConstant.SCOPE.ACCOUNT_BASEPROFILE),
Scope(Scopes.HEALTHKIT_STEP_BOTH),
Scope(Scopes.HEALTHKIT_HEIGHTWEIGHT_BOTH),
Scope(Scopes.HEALTHKIT_HEARTRATE_BOTH)
)
huaweiIdAuthParamsHelper.setScopeList(scopeList)
authParams = huaweiIdAuthParamsHelper.setAccessToken().createParams()
authService = HuaweiIdAuthManager.getService(this, authParams)
HEALTHKIT_STEP_BOTH → View and save step counts in HUAWEI Health Kit.
HEALTHKIT_HEIGHTWEIGHT_BOTH → View and save height and weight in HUAWEI Health Kit.
HEALTHKIT_HEARTRATE_BOTH → View and save the heart rate data in HUAWEI Health Kit.
For details about the mapping between scopes and permissions, see Scope in the API reference.After successfully sign process , we can move to crud and other operations. We are able to call ten methods in DataController to perform operations on the fitness and health data.The methods include:
insert: inserts data.
delete: deletes data.
update: updates data.
read: reads data.
readTodaySummation: queries the summarized data of the current day.
readTodaySummationFromDevice: queries the summarized data of the local device of the current day.
registerModifyDataMonitor: registers a listener for data updates.
unregisterModifyDataMonitor: unregisters a listener for data updates.
syncAll: syncs data between the device and cloud.
clearAll: clears data of the app from the device and cloud.
We need to create the data controller object before starting operations.
Code:
val hiHealthOptions = HiHealthOptions.builder()
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_CONTINUOUS_STEPS_DELTA, HiHealthOptions.ACCESS_WRITE)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_INSTANTANEOUS_HEIGHT, HiHealthOptions.ACCESS_WRITE)
.addDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT, HiHealthOptions.ACCESS_READ)
.addDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT, HiHealthOptions.ACCESS_WRITE)
.build()
val signInHuaweiId = HuaweiIdAuthManager.getExtendedAuthResult(hiHealthOptions)
dataController = HuaweiHiHealth.getDataController(this, signInHuaweiId)
Inserting Data
We build a DataCollector object to insert body weight.
Code:
val dataCollector: DataCollector = DataCollector.Builder().setPackageName(this)
.setDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT)
.setDataStreamName("BODY_WEIGHT_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build()
We will create a sampling dataset based on the data collector.
Code:
val sampleSet = SampleSet.create(dataCollector)
We will create the start time, end time, and weight value for a DT_INSTANTANEOUS_BODY_WEIGHT sampling point.The weight value must be in float format.
Code:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())val currentDate = dateFormat.format(Date())val startDate: Date = dateFormat.parse(currentDate)val endDate: Date = dateFormat.parse(currentDate)val samplePoint = sampleSet.createSamplePoint().setTimeInterval(startDate.time, endDate.time, TimeUnit.MILLISECONDS)samplePoint.getFieldValue(Field.FIELD_BODY_WEIGHT).setFloatValue(weight)
sampleSet.addSample(samplePoint)
And in this time, we need to call the data controller to insert the sampling dataset into the Health platform.
Code:
val insertTask: Task = dataController.insert(sampleSet)
insertTask.addOnSuccessListener {
Log.i("HomeFragment","Success insert a SampleSet into HMS core")
showSampleData(sampleSet, "Insert Weight")
}.addOnFailureListener { e ->
Toast.makeText(this, e.message.toString(), Toast.LENGTH_LONG).show()
}
If you examine the showSampleData function, you can see how the added data was reached.
Code:
private fun showSampleData(sampleSet: SampleSet, desc: String) {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for (samplePoint in sampleSet.samplePoints) {
Log.i("HomeFragment","Sample point type: " + samplePoint.dataType.name)
Log.i("HomeFragment", "Start: " + dateFormat.format(Date(samplePoint.getStartTime(TimeUnit.MILLISECONDS))))
Log.i("HomeFragment", "End: " + dateFormat.format(Date(samplePoint.getEndTime(TimeUnit.MILLISECONDS))))
for (field in samplePoint.dataType.fields) {
Log.i("HomeFragment", "Field: " + field.name + " Value: " + samplePoint.getFieldValue(field))
Toast.makeText(this, desc + samplePoint.getFieldValue(field), Toast.LENGTH_LONG).show()
}
}
}
Deleting Data
We will build a DataCollector object for data deletion.
Code:
val dataCollector: DataCollector = DataCollector.Builder().setPackageName(this)
.setDataType(DataType.DT_INSTANTANEOUS_BODY_WEIGHT)
.setDataStreamName("BODY_WEIGHT_DELTA")
.setDataGenerateType(DataCollector.DATA_TYPE_RAW)
.build()
After creating data collector object, we need to build the time range for the deletion: start time and end time.
Code:
val dateFormat = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault())
val startDate: Date = dateFormat.parse(startTimeEditText.text.toString())
val endDate: Date = dateFormat.parse(endTimeEditText.text.toString())
We build a parameter object as the conditions for the deletion while using DeleteOptions.So, the data in this time interval will be deleted.Also note that: Only historical data that has been inserted by the current app can be deleted from the Health platform.
Code:
val deleteOptions = DeleteOptions.Builder()
.addDataCollector(dataCollector)
.setTimeInterval(startDate.time, endDate.time, TimeUnit.MILLISECONDS)
.build()
And as last step, we use the specified condition deletion object to call the data controller to delete the sampling dataset.
Calling the data controller to delete the sampling dataset is an asynchronous operation. Therefore, a listener needs to be registered to monitor whether the data deletion is successful or not.
Code:
val deleteTask = dataController.delete(deleteOptions)
deleteTask.addOnSuccessListener {
Log.i("HomeFragment","Success delete steps data")
Toast.makeText([email protected], "Delete success", Toast.LENGTH_LONG).show()
}.addOnFailureListener {
Log.v(TAG, it.message.toString())
}
Updating Data
We will build a DataCollector object for data update.
This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/home
What is the difference between Huawei Health kit and Hihealth kit ?
Hello. Is there a way to correct data in the Huawei Health database?. For instance remove steps from a certain date?. Thank you!

Communicating Between JavaScript and Java Through the Cordova Plugins in HMS Core Kit

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 Call​You 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

Communicating Between JavaScript and Java Through the Cordova Plugins

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.
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.
Basic Structure of Cordova​When you call style='mso-bidi-font-weight:normal'>loadUrl in MainActivity, CordovaWebView will be initialized and Cordova starts up. In this case, style='mso-bidi-font-weight:normal'>CordovaWebView will create style='mso-bidi-font-weight:normal'>PluginManager, NativeToJsMessageQueue, as well as ExposedJsApi of JavascriptInterface. style='mso-bidi-font-weight:normal'>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.
Plugin Call
You 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 @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;
(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));
(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.
Code:
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";
Code:
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.
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.
References​For more details, you can go to:
HMS Core official website
HMS Core Cordova Plugin Development Documentation page, to find the documents you need
Reddit to join our developer discussion
GitHub to download Cordova Plugins
Stack Overflow to solve any integration problems
Thanks for sharing

Categories

Resources