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.
Related
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?
{
"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/
In the mobile Internet era, people are increasingly using mobile apps for a variety of different purposes, such as buying products online, hailing taxis, and much more. When using such an app, a user usually needs to manually enter their address for package delivery or search for an appropriate pick-up and drop-off location when they hail a taxi, which can be inconvenient.
To improve user experience, many apps nowadays allow users to select a point on the map and then use the selected point as the location, for example, for package delivery or getting on or off a taxi. Each location has a longitude-latitude coordinate that pinpoints its position precisely on the map. However, longitude-latitude coordinates are simply a string of numbers and provide little information to the average user. It would therefore be useful if there was a tool which an app can use to convert longitude-latitude coordinates into human-readable addresses.
Fortunately, the reverse geocoding function in HMS Core Location Kit can obtain the nearest address to a selected point on the map based on the longitude and latitude of the point. Reverse geocoding is the process of converting a location as described by geographic coordinates (longitude and latitude) to a human-readable address or place name, which is much more useful information for users. It permits the identification of nearby street addresses, places, and subdivisions such as neighborhoods, counties, states, and countries.
Generally, the reverse geocoding function can be used to obtain the nearest address to the current location of a device, show the address or place name when a user taps on the map, find the address of a geographic location, and more. For example, with reverse geocoding, an e-commerce app can show users the detailed address of a selected point on the map in the app; a ride-hailing or takeout delivery app can show the detailed address of a point that a user selects by dragging the map in the app or tapping the point on the map in the app, so that the user can select the address as the pick-up address or takeout delivery address; and an express delivery app can utilize reverse geocoding to show the locations of delivery vehicles based on the passed longitude-latitude coordinates, and intuitively display delivery points and delivery routes to users.
Bolstered by a powerful address parsing capability, the reverse geocoding function in this kit can display addresses of locations in accordance with local address formats with an accuracy as high as 90%. In addition, it supports 79 languages and boasts a parsing latency as low as 200 milliseconds.
{
"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"
}
DemoThe file below is a demo of the reverse geocoding function in this kit.
Preparations
Before getting started with the development, you will need to make the following preparations:
Register as a Huawei developer and complete identity verification on the HUAWEI Developers website. You can click here to find out the detailed registration and identity verification procedure.
Create a project and then create an app in the project in AppGallery Connect. Before doing so, you must have a Huawei developer account and complete identity verification.
Generate a signing certificate fingerprint and configure it in AppGallery Connect. The signing certificate fingerprint is used to verify the authenticity of an app. Before releasing an app, you must generate a signing certificate fingerprint locally based on the signing certificate and configure it in AppGallery Connect.
Integrate the Location SDK into your app. If you are using Android Studio, you can integrate the SDK via the Maven repository.
Here, I won't be describing how to generate and configure a signing certificate fingerprint and integrate the SDK. You can click here to learn about the detailed procedure.
Development Procedure
After making relevant preparations, you can perform the steps below to use the reverse geocoding service in your app. Before using the service, ensure that you have installed HMS Core (APK) on your device.
1. Create a geocoding service client.
In order to call geocoding APIs, you first need to create a GeocoderService instance in the onClick() method of GeocoderActivity in your project. The sample code is as follows:
Code:
Locale locale = new Locale("zh", "CN");
GeocoderService geocoderService = LocationServices.getGeocoderService(GeocoderActivity.this, locale);
2. Obtain the reverse geocoding information.
To empower your app to obtain the reverse geocoding information, you need to call the getFromLocation() method of the GeocoderService object in your app. This method will return a List<HWLocation> object containing the location information based on the set GetFromLocationRequest object.
a. Set reverse geocoding request parameters.
There are three request parameters in the GetFromLocationRequest object, which indicate the latitude, longitude, and maximum number of returned results respectively. The sample code is as follows:
Code:
// Parameter 1: latitude
// Parameter 2: longitude
// Parameter 3: maximum number of returned results
// Pass valid longitude-latitude coordinates. If the coordinates are invalid, no geographical information will be returned. Outside China, pass longitude-latitude coordinates located outside China and ensure that the coordinates are correct.
GetFromLocationRequest getFromLocationRequest = new GetFromLocationRequest(39.985071, 116.501717, 5);
b. Call the getFromLocation() method to obtain reverse geocoding information.
The obtained reverse geocoding information will be returned in a List<HWLocation> object. You can add listeners using the addOnSuccessListener() and addOnFailureListener() methods, and obtain the task execution result using the onSuccess() and onFailure() methods.
The sample code is as follows:
Code:
private void getReverseGeocoding() {
// Initialize the GeocoderService object.
if (geocoderService == null) {
geocoderService = new GeocoderService(this, new Locale("zh", "CN"));
}
geocoderService.getFromLocation(getFromLocationRequest)
.addOnSuccessListener(new OnSuccessListener<List<HWLocation>>() {
@Override
public void onSuccess(List<HWLocation> hwLocation) {
// TODO: Define callback for API call success.
if (null != hwLocation && hwLocation.size() > 0) {
Log.d(TAG, "hwLocation data set quantity: " + hwLocation.size());
Log.d(TAG, "CountryName: " + hwLocation.get(0).getCountryName());
Log.d(TAG, "City: " + hwLocation.get(0).getCity());
Log.d(TAG, "Street: " + hwLocation.get(0).getStreet());
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// TODO: Define callback for API call failure.
}
});
}
Congratulations, your app is now able to use the reverse geocoding function to obtain the address of a location based on its longitude and latitude.
Conclusion
The quick development and popularization of the mobile Internet has caused many changes to our daily lives. One such change is that more and more people are using mobile apps on a daily basis, for example, to buy daily necessities or hail a taxi. These tasks traditionally require users to manually enter the delivery address or pick-up and drop-off location addresses. Manually entering such addresses is inconvenient and prone to mistakes.
To solve this issue, many apps allow users to select a point on the in-app map as the delivery address or the address for getting on or off a taxi. However, the point on the map is usually expressed as a set of longitude-latitude coordinates, which most users will find hard to understand.
As described in this post, my app resolves this issue using the reverse geocoding function, which is proven a very effective way for obtaining human-readable addresses based on longitude-latitude coordinates. If you are looking for a solution to such issues, have a try to find out if this is what your app needs.
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.