More information like this, you can visit HUAWEI Developer Forum
Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate app messaging and analytics into demo flight booking application.
UseCase
1. We will show app-messaging image on app screen showing list of searched flight. When user tap on app-messaging image, it will redirect to webpage showing guidelines for international arrivals and departures. Add following image URL on Huawei App gallery connect.
{
"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. We will use Huawei analytics to report few events like successful sign in and number of flights available between source destination.
For prerequisite and set up, refer to part 1.
Huawei App messaging
App Messaging of AppGallery Connect used to send relevant messages to target users actively using your app to encourage them to use key app functions. For example, you can send in-app messages to encourage users to subscribe certain products, provide tips on passing a game level, or recommend activities of a restaurant.
Implemetation
1. Add dependency in the app build.gradle file.
Code:
dependencies {
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
}
2. We need AAID for later use in sending In-App Messages. To obtain AAID, we will use getAAID() method.
3. 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);
}
});
4. To initialize the AGConnectAppMessaging instance we will use.
Code:
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
5. To allow data synchronization from the AppGallery Connect server we will use.
Code:
appMessaging.setFetchMessageEnable(true);
6. To enable message display.
Code:
appMessaging.setDisplayEnable(true);
7. 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 data and time to stop sending message.
We can also display message on an events by using trigger event functionality.
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.
Huawei Analytics
In this section, will show you how to use main APIs of HUAWEI Analytics Kit to report some custom events. App will report event like successful login, number of search flights.
1. Add the dependencies in app build.gradle file.
Code:
implementation 'com.huawei.hms:hianalytics:5.0.1.301'
2. The MainActivity.java is launched once user has successfully signed in. In onCreate(), we will call initializeAnalytics()to report successful signed in event.
Code:
private void initializeAnalytics() {
//Enable Analytics Kit Log
HiAnalyticsTools.enableLog();
//Generate the Analytics Instance
instance = HiAnalytics.getInstance(this);
//Parameter definition
Bundle bundle = new Bundle();
bundle.putBoolean("IsLoggedIn", true);
//Reporting event
instance.onEvent("LoginStatus", bundle);
}
3. To report number of flight available between origin and destination.
Code:
httpHandler.setFlightSearchListner(new OnFightSearchListner() {
@Override
public void onSuccess(ArrayList<Quote> quoteList) {
if(quoteList!= null && quoteList.size() > 0) {
Bundle bundle = new Bundle();
bundle.putBoolean("FlightSearchStatus", true);
bundle.putInt("FlightSearchCount", quoteList.size());
//Reporting event
instance.onEvent("FlightSearchStatus", bundle);
}
adapter = new OneWayFlightAdapter(quoteList);
recyclerView.setAdapter(adapter);
}
@Override
public void OnFailure(Exception e) {
// not implemented yet.. will do later
Log.e(TAG, e.getMessage());
}
});
To Check Analysis on App Gallery Connect
1. On the left side panel, click on Huawei Analyze > Behaviour Analysis > Event Analysis.
Conclusion:
In this article, we learnt how to integrate Huawei app-messaging and analytics to report event in application.
Can we integrate push messages along with in-app messaging?
well explained, can we load gifs also?
Related
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.
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:
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.
{
"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"
}
As online shopping for products and services becomes more and more popular, new business opportunities have also arisen. To seize such opportunities, I recently developed an online shopping app, which I shall refer to in this article as "app B". Once you have developed an app, the next thing that you need to do is to promote the app and attract more users to use it. Since sending push messages to users is a widely used method for promoting apps and improving user engagement, I decided to do the same for my new app in order to deliver promotional information and various coupons to users, which hopefully should increase their engagement and interest.
However, I discovered a glaring problem straightaway. Since the app has just been released, it has few registered users, making it hard to achieve the desired promotional effect by just sending push messages to these users. What I needed to do was to send push messages to a large pool of existing users in order to get them to try out my new app. It suddenly occurred to me that I once developed a very popular short video app (which I shall refer to as "app A"), which has now accumulated thousands of registered users. Wouldn't it be great if there was a one-stop service that I can use to get app B to send push messages to the wide user base of app A, thus attracting users of app A to use app B?
Fortunately, I discovered that the multi-sender function in HMS Core Push Kit empowers different apps to send push messages to a specific app — a function that fits my situation perfectly. Therefore, I decided to integrate Push Kit and use its multi-sender function to allow app B to send promotional push messages and coupons to users of app A. The entire integration and configuration process of Push Kit's multi-sender function is straightforward, which I'll demonstrate below.
Integration ProcedurePreparations
Before using the multi-sender function, we'll need to integrate the Push SDK into app A. You can find the detailed integration guide here. In this article, I won't be describing the integration steps.
Configuring the Multi-sender Function
After integrating the SDK into app A, we then need to configure the multi-sender function for app B. The detailed procedure is as follows:
1. Sign in to AppGallery Connect, click My projects, and click the project to which app B belongs. Then, go to Grow > Push Kit > Settings, select app B, and view and record the sender ID of app B (ID of the project to which app B belongs), as shown in the screenshot below. Note that the sender ID is the same as the project ID.
2. Switch to the project to which app A belongs, select app A, and click Add in the Multiple senders area.
3. In the dialog box displayed, enter the sender ID of app B and click Save.
After doing so, app B acquires the permission to send push messages to app A.
On the permission card displayed under Multiple senders, we can specify whether to allow app B to send push messages to app A as required.
Applying for a Push Token for App B
After configuring the multi-sender function, we need to make some changes to app A.
1. Obtain the agconnect-services.json file of app A from AppGallery Connect, and copy the file to the root directory of app A in the project.
Note that the agconnect-services.json file must contain the project_id field. If the file does not contain the field, you need to download the latest file and replace the existing file with the latest one. Otherwise, an error will be reported when getToken() is called.
2. Call the getToken() method in app A to apply for a push token for app B.
The sample code is as follows. Note that projectId in the sample code indicates the sender ID of app B.
Code:
public class MainActivity extends AppCompatActivity {
private void getSubjectToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Set the project ID of the sender (app B).
String projectId = "Sender ID";
// Apply for a token for the sender (app B).
String token = HmsInstanceId.getInstance(MainActivity.this).getToken(projectId);
Log.i(TAG, "get token:" + token);
// Check whether the push token is empty.
if(!TextUtils.isEmpty(token)) {
sendRegTokenToServer(token);
}
} catch (ApiException e) {
Log.e(TAG, "get token failed, " + e);
}
}
}.start();
}
private void sendRegTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
}
Sending Push Messages to App AAfter obtaining the push token, app A will send the push token to app B. Then, app B can send push messages to app A based on an access token.
Follow the instructions here to obtain an access token for the sender (app B).
Call the downlink messaging API in app B to send push messages to app A.
The URL for calling the API using HTTPS POST is as follows:
Code:
POST https://push-api.cloud.huawei.com/v2/projectid/messages:send
In the URL, projectid indicates the sender ID of app B.
The following is an example of the downlink message body:
Code:
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 3
}
}
},
"token": ["Push token applied for the sender"]
}
}
Now, app B can send push messages to users of app A.
Conclusion
User acquisition is an inevitable challenge for newly developed apps, but is also the key for the new apps to achieve business success. Driven by this purpose, developers usually take advantage of all available resources, including sending promotional push messages to acquire users for their new apps. However, these developers usually encounter the same problem, that is, where to find potential users and how to send push messages to such users.
In this article, I demonstrated how I solve this challenge by utilizing Push Kit's multi-sender function, which allows my newly developed app to send promotional push messages to the large use base of an existing app to quickly acquire its users. The whole integration process is straightforward and cost-efficient, and is an effective way to allow multiple apps to send push messages to a specific app.
As online shopping for products and services becomes more and more popular, new business opportunities have also arisen. To seize such opportunities, I recently developed an online shopping app, which I shall refer to in this article as "app B". Once you have developed an app, the next thing that you need to do is to promote the app and attract more users to use it. Since sending push messages to users is a widely used method for promoting apps and improving user engagement, I decided to do the same for my new app in order to deliver promotional information and various coupons to users, which hopefully should increase their engagement and interest. However, I discovered a glaring problem straightaway. Since the app has just been released, it has few registered users, making it hard to achieve the desired promotional effect by just sending push messages to these users. What I needed to do was to send push messages to a large pool of existing users in order to get them to try out my new app. It suddenly occurred to me that I once developed a very popular short video app (which I shall refer to as "app A"), which has now accumulated millions of registered users. Wouldn't it be great if there was a one-stop service that I can use to get app B to send push messages to the wide user base of app A, thus attracting users of app A to use app B? Fortunately, I discovered that the multi-sender function in HMS Core Push Kit empowers different apps to send push messages to a specific app — a function that fits my situation perfectly. Therefore, I decided to integrate Push Kit and use its multi-sender function to allow app B to send promotional push messages and coupons to users of app A.
The entire integration and configuration process of Push Kit's multi-sender function is straightforward, which I'll demonstrate below.
Integration ProcedureI. PreparationsBefore using the multi-sender function, we'll need to integrate the Push SDK into app A. You can find the detailed integration guide here. In this article, I won't be describing the integration steps.
II. Configuring the Multi-sender FunctionAfter integrating the SDK into app A, we then need to configure the multi-sender function for app B. The detailed procedure is as follows:
1. Sign in to AppGallery Connect, click My projects, and click the project to which app B belongs. Then, go to Grow > Push Kit > Settings, select app B, and view and record the sender ID of app B (ID of the project to which app B belongs), as shown in the screenshot below. Note that the sender ID is the same as the project ID.
{
"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. Switch to the project to which app A belongs, select app A, and click Add in the Multiple senders area.
3. In the dialog box displayed, enter the sender ID of app B and click Save.
After doing so, app B acquires the permission to send push messages to app A.
On the permission card displayed under Multiple senders, we can specify whether to allow app B to send push messages to app A as required.
III. Applying for a Push Token for App BAfter configuring the multi-sender function, we need to make some changes to app A.
1. Obtain the agconnect-services.json file of app A from AppGallery Connect, and copy the file to the root directory of app A in the project.
Note that the agconnect-services.json file must contain the project_id field. If the file does not contain the field, you need to download the latest file and replace the existing file with the latest one. Otherwise, an error will be reported when getToken() is called.
2. Call the getToken() method in app A to apply for a push token for app B.
The sample code is as follows. Note that projectId in the sample code indicates the sender ID of app B.
Code:
public class MainActivity extends AppCompatActivity {
private void getSubjectToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Set the project ID of the sender (app B).
String projectId = "Sender ID";
// Apply for a token for the sender (app B).
String token = HmsInstanceId.getInstance(MainActivity.this).getToken(projectId);
Log.i(TAG, "get token:" + token);
// Check whether the push token is empty.
if(!TextUtils.isEmpty(token)) {
sendRegTokenToServer(token);
}
} catch (ApiException e) {
Log.e(TAG, "get token failed, " + e);
}
}
}.start();
}
private void sendRegTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
}
IV. Sending Push Messages to App AAfter obtaining the push token, app A will send the push token to app B. Then, app B can send push messages to app A based on an access token.
1. Follow the instructions here to obtain an access token for the sender (app B).
2. Call the downlink messaging API in app B to send push messages to app A.
The URL for calling the API using HTTPS POST is as follows:
Code:
POST https://push-api.cloud.huawei.com/v2/projectid/messages:send
In the URL, projectid indicates the sender ID of app B.
The following is an example of the downlink message body:
Code:
{
"validate_only": false,
"message": {
"android": {
"notification": {
"title": "test title",
"body": "test body",
"click_action": {
"type": 3
}
}
},
"token": ["Push token applied for the sender"]
}
}
Now, app B can send push messages to users of app A.
ConclusionUser acquisition is an inevitable challenge for newly developed apps, but is also the key for the new apps to achieve business success. Driven by this purpose, developers usually take advantage of all available resources, including sending promotional push messages to acquire users for their new apps. However, these developers usually encounter the same problem, that is, where to find potential users and how to send push messages to such users.
In this article, I demonstrated how I solve this challenge by utilizing Push Kit's multi-sender function, which allows my newly developed app to send promotional push messages to the large use base of an existing app to quickly acquire its users. The whole integration process is straightforward and cost-efficient, and is an effective way to allow multiple apps to send push messages to a specific app.
MOD ACTION:
Thread closed as duplicate of https://forum.xda-developers.com/t/...ush-messages-to-users-of-another-app.4470267/
During workouts, users expect to be able to track their status and data in real time within the health or fitness app on their phone. Huawei phone users can link a piece of equipment, like a treadmill or spinner bike, via the Huawei Health app, and start and track their workout within the app. As a fitness and health app developer, you can read activity records from the Huawei Health app, and display the records in your app. It is even possible to control the workout status directly within your app, and obtain real-time activity data, without having to redirect users to the Huawei Health app, which helps users conveniently track their workout and greatly enhances the user experience. Here is how.
HMS Core Health Kit provides a wide range of capabilities for fitness and health app developers. Its extended capabilities open up a wealth of real time activity and health data and solutions specific to different scenarios. For example, after integrating the extended capabilities, you can call the APIs for starting, pausing, resuming, and stopping activities, to control activity status directly within your app, without redirecting users to the Huawei Health app. The Huawei Health app runs unobtrusively in the background throughout this entire process.
The extended capabilities also offer APIs for obtaining and halting the collection of real-time workout data. To prevent data loss, your app should call the API for obtaining real-time data before the workout starts, and avoid calling the API for halting the collection of real-time data before the workout ends. If the user links their phone with a Huawei wearable device via the Huawei Health app, the workout status in your app will be synched to the wearable device. This means that the wearable device will automatically display the workout screen when the user starts a workout in your app, and will stop displaying it as soon as the workout is complete. Make sure that you have applied for the right scopes from Huawei and obtained the authorization from users before API calling. Otherwise, API calling will fail. The following workouts are currently supported: outdoor walking, outdoor running, outdoor cycling, indoor running (on a treadmill), elliptical machine, rowing machine, and indoor cycling.
{
"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"
}
Redirecting to the device pairing screen
Demo
PreparationsApplying for Health KitBefore applying for Health Kit, you will need to apply for Account Kit first.
Integrating the HMS Core SDKBefore integrating the Health SDK, integrate the Account SDK first.
Before getting started, you need to integrate the HMS Core SDK into your app using Android Studio. Make sure that you use Android Studio V3.3.2 or later during the integration of Health Kit.
Development ProcedureStarting Obtaining Real-time Activity Data1. Call the registerSportData method of the HiHealthDataStore object to start obtaining real time activity data.
2. Check the returned result through the request parameter HiSportDataCallback.
The sample code is as follows:
Code:
HiHealthDataStore.registerSportData(context, new HiSportDataCallback() {
@Override
public void onResult(int resultCode) {
// API calling result.
Log.i(TAG, "registerSportData onResult resultCode:" + resultCode);
}
@Override
public void onDataChanged(int state, Bundle bundle) {
// Real-time data change callback.
Log.i(TAG, "registerSportData onChange state: " + state);
StringBuffer stringBuffer = new StringBuffer("");
if (state == HiHealthKitConstant.SPORT_STATUS_RUNNING) {
Log.i(TAG, "heart rate : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_HEARTRATE));
Log.i(TAG, "distance : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DISTANCE));
Log.i(TAG, "duration : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_DURATION));
Log.i(TAG, "calorie : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_CALORIE));
Log.i(TAG, "totalSteps : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_STEPS));
Log.i(TAG, "totalCreep : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_CREEP));
Log.i(TAG, "totalDescent : " + bundle.getInt(HiHealthKitConstant.BUNDLE_KEY_TOTAL_DESCENT));
}
}
});
Stopping Obtaining Real-time Activity Data1. Call the unregisterSportData method of the HiHealthDataStore object to stop obtaining the real time activity data.
2. Check the returned result through the request parameter HiSportDataCallback.
The sample code is as follows:
Code:
HiHealthDataStore.unregisterSportData(context, new HiSportDataCallback() {
JSONObject jsonResult
@Override
public void onResult(int resultCode) {
// API calling result.
Log.i(TAG, "unregisterSportData onResult resultCode:" + resultCode);
}
@Override
public void onDataChanged(int state, Bundle bundle) {
// The API is not called at the moment.
}
});
Starting an Activity According to the Activity Type1. Call the startSport method of the HiHealthDataStore object to start a specific type of activity.
2. Use the ResultCallback object as a request parameter to get the query result.
The sample code is as follows:
Code:
// Outdoor running.
int sportType = HiHealthKitConstant.SPORT_TYPE_RUN;
HiHealthDataStore.startSport(context, sportType, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "start sport success");
}
}
});
3. For activities that depend on equipment like treadmills, rowing machines, elliptical machines, and stationary bikes, you will need to first check whether the relevant equipment has been paired in the Huawei Health app before starting the activity. The following uses a rowing machine as an example.
If there is one rowing machine paired, this machine will be connected by default, and the activity will then start in the background.
If the app is paired with more than one rowing machines, a pop-up window will display prompting the user to select a machine. After the user makes their choice, the window will disappear and the workout will start in the background.
If the app is not paired with any rowing machine, the user will be redirected to the device pairing screen in the Huawei Health app, before being returned to your app. The workout will then start in the background.
Starting an Activity Based on the Device Information1. Call the startSportEx method of the HiHealthDataStore object, and pass the StartSportParam parameter for starting the activity. You can control whether to start the activity in the foreground or in the background by setting CharacteristicConstant.SportModeType.
2. Use the ResultCallback object as a request parameter to get the activity starting result.
The sample code is as follows:
Code:
// The following takes the rowing machine as an example.
// MAC address, with every two digits separated by a colon (:), for example, 11:22:33:44:55:66.
String macAddress = "11:22:33:44:55:66" ;
// Whether FTMP is supported. 0: no; 1: yes.
int isSupportedFtmp = CharacteristicConstant.FtmpType.FTMP_SUPPORTED.getFtmpTypeValue();
// Device type: rowing machine.
int deviceType = CharacteristicConstant.DeviceType.TYPE_ROWER_INDEX.getDeviceTypeValue();
// Activity type: rowing machine.
int sportType = CharacteristicConstant.EnhanceSportType.SPORT_TYPE_ROW_MACHINE.getEnhanceSportTypeValue();
// Construct startup parameters for device connection and activity control.
StartSportParam param = new StartSportParam(macAddress, isSupportedFtmp, deviceType, sportType);
// Whether to start the activity in the foreground (0) or background (1).
param.putInt(HiHealthDataKey.IS_BACKGROUND,
CharacteristicConstant.SportModeType.BACKGROUND_SPORT_MODE.getType());
HiHealthDataStore.startSportEx(mContext, param, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "start sportEx success");
}
}
});
Stopping an Activity1. Call the stopSport method of the HiHealthDataStore object to stop a specific type of activity. Note that you cannot use this method to stop activities started in the foreground.
2. Use the ResultCallback object as a request parameter to get the query result.
The sample code is as follows:
Code:
HiHealthDataStore.stopSport(context, new ResultCallback() {
@Override
public void onResult(int resultCode, Object message) {
if (resultCode == HiHealthError.SUCCESS) {
Log.i(TAG, "stop sport success");
}
}
});
ConclusionHuawei phone users can use the Huawei Health app to bind wearable devices, start a workout and control their workout status, and track their workouts over time. When developing a fitness and health app, you can harness the capabilities in Health Kit and the Huawei Health app to get the best of all worlds: easy workout management free of annoying redirections. By calling the APIs provided by the kit's extended capabilities, you will be able to start, pause, resume, and stop workouts directly in your app, or obtain real time workout data from the Huawei Health app and display it in your app, with Huawei Health running in the background. This will considerably enhance the user experience, and make your fitness and health app much more appealing to a wider audience.
ReferencesHMS Core Health Kit Development Guide
Bundle Keys for Real-time Activity
Applying for the HUAWEI ID Service
Smartphones are everywhere these days and play an important role in our daily lives. The popularization of smartphones has led to a wave of mobile apps hitting the market. So, the homogeneous competition between apps is more fierce than ever and developers are trying their best to figure out how best to attract users to their apps. Most developers resort to message pushing, which leads to an exponential growth of pushed messages. As a result, users quickly become flooded with pushed messages and struggle to find the information they need.
The explosion of pushed messages means that crafting eye-catching messages that appeal to users has never been more crucial and challenging. Like many other developers, I also encountered this problem. I have pushed many promotional messages to users of my app, but the outcome is not particularly positive. So I wondered if it is possible to push messages only to a specific user group, for example, sending car-related product promotion messages to users with cars.
It occurred to me that I came across HMS Core Push Kit, which provides a function that allows developers to send topic-based messages. With this function, developers can customize messages by topic to match users' habits or interests and then regularly send these messages to user devices via a push channel. For example, a weather forecast app can send weather forecast messages concerning a city that users have subscribed to, or a movie ticket-booking app can send reminders to users who have followed a particular movie.
Isn't that exactly what I need? So I decided to play about with this function, and it turned out to be very effective. Below is a walkthrough of how I integrated this function into my app to send topic-based messages. I hope this will help you.
Development Procedure
Generally, three development steps are required for using the topic-based messaging function.
Step 1: Subscribe to a topic within the app.
Step 2: Send a message based on this topic.
Step 3: Verify that the message has been received.
The figure below shows the process of messaging by topic subscription on the app server.
{
"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"
}
You can manage topic subscriptions in your app or on your app server. I will detail the procedures and codes for both of these methods later.
Key Steps and Coding
Managing Topic Subscription in Your App
The following is the sample code for subscribing to a topic:
Code:
public void subtopic(View view) {
String SUBTAG = "subtopic";
String topic = "weather";
try {
// Subscribe to a topic.
HmsMessaging.getInstance(PushClient.this).subscribe(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(SUBTAG, "subscribe topic weather successful");
} else {
Log.e(SUBTAG, "subscribe topic failed,return value is" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(SUBTAG, "subscribe faied,catch exception:" + e.getMessage());
}
}
The figure below shows that the topic is successfully subscribed to.
The following is the sample code for unsubscribing from a topic:
Code:
public void unsubtopic(View view) {
String SUBTAG = "unsubtopic";
String topic = "weather";
try {
// Subscribe to a topic.
HmsMessaging.getInstance(PushClient.this).unsubscribe(topic).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
Log.i(SUBTAG, "unsubscribe topic successful");
} else {
Log.e(SUBTAG, "unsubscribe topic failed,return value is" + task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(SUBTAG, "subscribe faied,catch exception:" + e.getMessage());
}
}
The figure below shows that the topic is successfully unsubscribed from.
Managing Topic Subscription on Your App Server
Obtaining an Access Token
You can call the API (https://oauth-login.cloud.huawei.com/oauth2/v3/token) of the HMS Core Account Kit server to obtain an app-level access token for authentication.
Request for obtaining an access token
Code:
POST /oauth2/v3/token HTTP/1.1
Host: oauth-login.cloud.huawei.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&
client_id=<APP ID >&
client_secret=<APP secret >
Demonstration of obtaining an access token
Subscribing to and Unsubscribe from Topics
Your app server can subscribe to or unsubscribe from a topic for your app by calling the corresponding subscription and unsubscription APIs of the Push Kit server. The URLs of the subscription and unsubscription APIs differ slightly, but the header and body of the subscription request are the same as those of the unsubscription request. The details are as follows:
URL of the subscription API
Code:
https://push-api.cloud.huawei.com/v1/[appid]/topic:subscribe
URL of the unsubscription API
Code:
https://push-api.cloud.huawei.com/v1/[appid]/topic:unsubscribe
Example of the request header, where the token following Bearer is the access token obtained in the previous step
Code:
Authorization: Bearer CV0kkX7yVJZcTi1i+uk...Kp4HGfZXJ5wSH/MwIriqHa9h2q66KSl5
Content-Type: application/json
Example of the request body
Code:
{
"topic": "weather",
"tokenArray": [
"AOffIB70WGIqdFJWJvwG7SOB...xRVgtbqhESkoJLlW-TKeTjQvzeLm8Up1-3K7",
"AKk3BMXyo80KlS9AgnpCkk8l...uEUQmD8s1lHQ0yx8We9C47yD58t2s8QkOgnQ"
]
}
Request demonstration
Sending Messages by Topic
You can send messages based on a created topic through the HTTPS protocol. The sample code for HTTPS-based messaging is as follows:
Code:
{
"validate_only": false,
"message": {
"notification": {
"title": "message title",
"body": "message body"
},
"android": {
"notification": {
"click_action": {
"type": 1,
"action": "com.huawei.codelabpush.intent.action.test"
}
}
},
"topic": "weather"
}
}
The figure below shows that the message is received and displayed on the user device.
Precautions
1. Your app can subscribe to any existing topics, or create new topics. When subscribing to a topic that does not exist, your app will request Push Kit to create such a topic. Then, any other app can subscribe to this topic.
2. The Push Kit server provides basic APIs for managing topics. You can subscribe to or unsubscribe from a topic using a maximum of 1000 tokens at a time. Each app can have a maximum of 2000 different topics.
3. The subscription relationship between the topic and token takes effect one minute after the subscription is complete. After the subscription takes effect, you'll be able to specify one topic, or a set of topic matching conditions to send messages in batches.
That's all for integrating the topic-based messaging function. In addition to this function, I also found that Push Kit provides functions such as scenario-based messaging and geofence-based messaging, which I think are very useful because they allow apps to push messages that are suitable for users' scenarios to users.
For example, with the scenario-based messaging function, an app can automatically send messages to users by scenario, such as when headsets are inserted, the Bluetooth car stereo is disconnected, or the motion status changes. With the geofence-based messaging function, an app can send messages to users by location, such as when users enter a shopping mall or airport and stay there for a specified period of time.
These functions, I think, can help apps improve user experience and user engagement. If you want to try out these functions, click here to view the official website.
Conclusion
The key to a successful app that stands out from the crowd is crafting messages that immediately grasp users' attention. This requires customizing messages by topic to match users' habits or interests, then regularly sending these messages to user devices via a push channel. As I illustrated earlier in this article, my solution for doing so is to integrate the topic-based messaging function in Push Kit, and it turns out to be very effective. If you have similar demands, have a try on this function and you may be surprised.