Reel in Users with Topic-based Messaging - Huawei Developers

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.

Related

Huawei Flight Booking Application (App messaging and analytics integration) – Part 2

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?

Implementing Message Push for Your Quick App Rapidly

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.

How to Help College Students Avoid Phone Scams

View attachment Featured image.jpg
As the start of the new academic year approaches, many college students will be leaving their parents to start college life. However, a lack of experience makes it easy for college students to become victims of electronic fraud such as phone scams.
The start of the new academic year is often a period of time that sees an uptick in phone scams, especially those targeting college students. Some scammers trick students to download and register an account on malicious financial apps embedded with viruses and Trojan horses or ones that imitate legitimate apps. With such malicious apps installed on students' phones, scammers are able to steal students' sensitive data, such as bank card numbers and passwords. Some scammers trick students, by offering them small gifts or coupons, to scan QR codes which then direct them to pages that ask users to enter their personal information, such as their phone number and address. Once a student has done this, they will receive a large number of fraudulent calls and junk SMS messages from then on. If the students scan QR codes linking to phishing websites, their personal data may be leaked and sold for malicious purposes. Some scammers even lie about offering students scholarships or grants, in order to trick them into visiting phishing websites and entering their bank account numbers and passwords, causing significant financial losses to such students.
{
"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"
}
To deal with the ever-changing tricks of fraudsters, an app needs to detect phishing websites, malicious apps, and other risks and remind users to be on the lookout for such risks with in-app tips, in order to keep users and their data safe. So, is there a one-stop service that can enhance app security from multiple dimensions? Fortunately, HMS Core Safety Detect can help developers quickly build security capabilities into their apps, and help vulnerable user groups such as college students safeguard their information and property.
The AppsCheck API in Safety Detect allows your app to obtain a list of malicious apps installed on a user's device. The API can identify 99% of malicious apps and detect unknown threats based on app behavior. Your app can then use this information to determine whether to restrict users from performing in-app payments and other sensitive operations.
The URLCheck API in Safety Detect checks whether an in-app URL is malicious. If the URL is determined to be malicious, the app can warn the user of the risk or block the URL.
Safety Detect also provides capabilities to check system integrity and detect fake users, helping developers quickly improve their app security. The integration process is straightforward, which I'll describe below.
Demo​
Integration Procedure​Preparations​You can follow the instructions here to prepare for the integration.
Using the AppsCheck API​You can directly call getMaliciousAppsList of SafetyDetectClient to obtain a list of malicious apps. The sample code is as follows:
Code:
private void invokeGetMaliciousApps() {
SafetyDetectClient appsCheckClient = SafetyDetect.getClient(MainActivity.this);
Task task = appsCheckClient.getMaliciousAppsList();
task.addOnSuccessListener(new OnSuccessListener<MaliciousAppsListResp>() {
@Override
public void onSuccess(MaliciousAppsListResp maliciousAppsListResp) {
// Indicates that communication with the service was successful.
// Use resp.getMaliciousApps() to obtain a list of malicious apps.
List<MaliciousAppsData> appsDataList = maliciousAppsListResp.getMaliciousAppsList();
// Indicates that the list of malicious apps was successfully obtained.
if(maliciousAppsListResp.getRtnCode() == CommonCode.OK) {
if (appsDataList.isEmpty()) {
// Indicates that no known malicious apps were detected.
Log.i(TAG, "There are no known potentially malicious apps installed.");
} else {
Log.i(TAG, "Potentially malicious apps are installed!");
for (MaliciousAppsData maliciousApp : appsDataList) {
Log.i(TAG, "Information about a malicious app:");
// Use getApkPackageName() to obtain the APK name of the malicious app.
Log.i(TAG, "APK: " + maliciousApp.getApkPackageName());
// Use getApkSha256() to obtain the APK SHA-256 of the malicious app.
Log.i(TAG, "SHA-256: " + maliciousApp.getApkSha256());
// Use getApkCategory() to obtain the category of the malicious app.
// Categories are defined in AppsCheckConstants.
Log.i(TAG, "Category: " + maliciousApp.getApkCategory());
}
}
}else{
Log.e(TAG,"getMaliciousAppsList failed: "+maliciousAppsListResp.getErrorReason());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// An error occurred during communication with the service.
if (e instanceof ApiException) {
// An error with the HMS API contains some
// additional details.
ApiException apiException = (ApiException) e;
// You can retrieve the status code using the apiException.getStatusCode() method.
Log.e(TAG, "Error: " + SafetyDetectStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " + apiException.getStatusMessage());
} else {
// A different, unknown type of error occurred.
Log.e(TAG, "ERROR: " + e.getMessage());
}
}
});
}
Using the URLCheck API​1. Initialize the URLCheck API.
Before using the URLCheck API, you must call the initUrlCheck method to initialize the API. The sample code is as follows:
Code:
SafetyDetectClient client = SafetyDetect.getClient(getActivity());
client.initUrlCheck();
2. Request a URL check.
You can pass target threat types to the URLCheck API as parameters. The constants in the UrlCheckThreat class include the current supported threat types.
Code:
public class UrlCheckThreat {
// URLs of this type are marked as URLs of pages containing potentially malicious apps (such as home page tampering URLs, Trojan-infected URLs, and malicious app download URLs).
public static final int MALWARE = 1;
// URLs of this type are marked as phishing and spoofing URLs.
public static final int PHISHING = 3;
}
a. Initiate a URL check request.
The URL to be checked contains the protocol, host, and path but does not contain the query parameter. The sample code is as follows:
Code:
String url = "https://developer.huawei.com/consumer/cn/";
SafetyDetect.getClient(this).urlCheck(url, appId, UrlCheckThreat.MALWARE, UrlCheckThreat.PHISHING).addOnSuccessListener(this, new OnSuccessListener<UrlCheckResponse >(){
@Override
public void onSuccess(UrlCheckResponse urlResponse) {
if (urlResponse.getUrlCheckResponse().isEmpty()) {
// No threat exists.
} else {
// Threats exist.
}
}
}).addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// An error occurred during communication with the service.
if (e instanceof ApiException) {
// HMS Core (APK) error code and corresponding error description.
ApiException apiException = (ApiException) e;
Log.d(TAG, "Error: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()));
// Note: If the status code is SafetyDetectStatusCode.CHECK_WITHOUT_INIT,
// you did not call the initUrlCheck() method or you have initiated a URL check request before the call is completed.
// If an internal error occurs during the initialization, you need to call the initUrlCheck() method again to initialize the API.
} else {
// An unknown exception occurred.
Log.d(TAG, "Error: " + e.getMessage());
}
}
});
b. Call the getUrlCheckResponse method of the returned UrlCheckResponse object to obtain the URL check result.
The result contains List<UrlCheckThreat>, which includes the detected URL threat type. If the list is empty, no threat is detected. Otherwise, you can call getUrlCheckResult in UrlCheckThreat to obtain the specific threat code. The sample code is as follows:
Code:
final EditText testRes = getActivity().findViewById(R.id.fg_call_urlResult);
List<UrlCheckThreat> list = urlCheckResponse.getUrlCheckResponse();
if (list.isEmpty()) {
testRes.setText("ok");
}
else{
for (UrlCheckThreat threat : list) {
int type = threat.getUrlCheckResult();
}
}
3. Close the URL check session.
If your app does not need to call the URLCheck API anymore or will not need to for a while, you can call the shutdownUrlCheck method to close the URL check session and release relevant resources.
Code:
SafetyDetect.getClient(this).shutdownUrlCheck();
Conclusion​Electronic fraud such as phone scams are constantly evolving and becoming more and more difficult to prevent, bringing great challenges to both developers and users. To combat such risks, developers must utilize technical means to identify phishing websites, malicious apps, and other risks, in order to safeguard users' personal information and property.
In this article, I demonstrated how HMS Core Safety Detect can be used to effectively combat electronic fraud. The whole integration process is straightforward and cost-efficient, and is a quick and effective way to build comprehensive security capabilities into an app.

How Can an App Send Push Messages to Users of Another 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"
}
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 Procedure​​Preparations​
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 A​After 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.

[CLOSED] How Can an App Send Push Messages to Users of Another 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 Procedure​I. Preparations​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.
II. 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.
{
"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 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);
}
}
IV. Sending Push Messages to App A​After 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.
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.
MOD ACTION:
Thread closed as duplicate of https://forum.xda-developers.com/t/...ush-messages-to-users-of-another-app.4470267/

Categories

Resources