0% found this document useful (0 votes)
137 views37 pages

Introduction To HMS Core Push Kit

This document provides an introduction and overview of the key aspects of HMS Core Push Kit for sending push notifications. It discusses the advantages of Push Kit, the required settings to integrate Push Kit into an app, important APIs, and answers some frequently asked questions. The document is intended to help developers understand and implement Push Kit for pushing real-time messages from the cloud to users across Android, iOS, and web platforms.

Uploaded by

Nicholas V.T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views37 pages

Introduction To HMS Core Push Kit

This document provides an introduction and overview of the key aspects of HMS Core Push Kit for sending push notifications. It discusses the advantages of Push Kit, the required settings to integrate Push Kit into an app, important APIs, and answers some frequently asked questions. The document is intended to help developers understand and implement Push Kit for pushing real-time messages from the cloud to users across Android, iOS, and web platforms.

Uploaded by

Nicholas V.T
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Introduction to HMS Core Push Kit

1. An Introduction to HMS Push Kit


2. Advantages of Push Kit
3. HMS Push Kit Required Settings
C O N T E N T S 4. Key APIs of Push Kit
5. Push Kit Console
6. FAQ
7. Some Useful Links
01
An Introduction to HMS Push Kit
HMS Push is a backend service that provided by HUAWEI for developers. HMS Push Kit is a
messaging service which sets up a messaging channel from cloud to devices. Via push kit,
developers can send messages to apps on user’s devices in real time including Android, iOS and
Web platforms. This helps developers to remain closer ties with users and increases user
awareness of the app and engagement. That will help your app to be more intriguing and
reduce the possibility of users to delete it..
Types of messages supported by HUAWEI Push Kit

Notification messages
Data messages
02
Advantages of HMS Push Kit

Reliable Precise Rich formats Cross Platform


 Arrival rate 99%  By topic  Short text style  React
 10 million  By user tag  Big text style  Xamarin
message/s  Scheduled push  Big picture style  Flutter
 230+ countries  Multi-language
 Real-time feedback display
Reliable Quick Global
Arrival rate 99% Sending Speed

Notifications can be 10 million messages/sec 230+ countries


received even if your app Ten of billons every day
is not running
Low power Consumption
High delivery rate
Real time receipt
Message caching
By topic By user tag Scheduled push

Pushes message Can send notification to user at


Based on device ,
related to topics scheduled time .
targeted user
subscribed by user App gallery connect
Regular Style

Text style
Badges
Customized Style
Notification messages can be
displayed in various styles Button style

Ringtones
03 HMS Push Kit
Required Settings
 Create an app or project in the Huawei app gallery connect.

 Provide the SHA Key and App Package name of the android project in App Information Section.

 Provide storage location in convention section under project setting.

 Enable Push Kit setting in Manage APIs section.

 Download the agconnect-services.json from App Information Section. Add the json file in the app
folder of the android project.

 Add the maven url inside the repositories of buildscript and allprojects respectively (project
build.gradle file)
maven { url 'http://developer.huawei.com/repo/' }

 Add the class path inside the dependency section of project build.gradle file.

classpath 'com.huawei.agconnect:agcp:1.4.1.300'

 Add the plugin in the app build.gradle file

apply plugin: 'com.huawei.agconnect'


 Add below library in the app build.gradle file dependencies section.

implementation 'com.huawei.hms:push:{version}

 Sync the gradle.

Replace {version} with the actual SDK version number, for


example, implementation 'com.huawei.hms:push:5.0.4.302‘
Configuring the Manifest File
After integrating the SDK, register your service under application in
the AndroidManifest.xml file, inherit the HmsMessageService class, and implement the methods
in the class.

<service
android:name=".DemoHmsMessageService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
</intent-filter>
</service>

This service is used to receive data message and obtaining tokens

The above code uses the DemoHmsMessageService class as an example (the class name is
customized).
The exported attribute must be set to false to prevent components of other apps from
enabling
the service.
04
Steps 1 and 2: An app integrated with the HMS SDK obtain a push token.
Steps 3: The app reports the obtained push token to the app server.
Steps 4: The app server uses the push token to call APIs of the HUAWEI Push Kit server to send
messages.
Steps 5: The HUAWEI Push Kit server sends the messages to devices and the devices receive the
messages. For details, Steps 6 and 7: When the HUAWEI Push Kit server detects responses from the
devices, it sends a message receipt to the app server.
 After integrating the HMS Core Push SDK, apply for a token.
 Each app has a unique push token on each device. The client calls the getToken method
in HmsInstanceId to obtain the token from the Push Kit server.
 Then the app server sends messages to the app based on the token. You can upload tokens
to the token list on your app server for Sending messages. Your app server can then call the
push API of the Push Kit server to send messages to apps in batches based on the tokens.
private void getToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Obtain the app ID from the agconnect-service.json file.
String appId =
AGConnectServicesConfig.fromContext(MainActivity.this).getString("client/app_id");
// Enter the token ID HCM.
String tokenScope = "HCM";
String token = HmsInstanceId.getInstance(MainActivity.this).getToken(appId, tokenScope);
Log.i(TAG, "get token: " + token);

// Check whether the 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);
}
Scenarios where a token may change include but are not limited to the following:
 An app is reinstalled.
 An app calls the API for deleting the token.
 A user restores the device to its factory settings.
 App data is deleted.

Override the onNewToken method. When a token changes or the EMUI version is earlier than
10.0, call the onNewToken method to return a token.
@Override
public void onNewToken(String token) {
// Obtain a token.
Log.i(TAG, "received refresh token:" + token);

// Check whether the token is empty.


if (!TextUtils.isEmpty(token)) {
refreshedTokenToServer(token);
}
}
private void refreshedTokenToServer(String token) {
Log.i(TAG, "sending token to server. token:" + token);
}
If you do not want your app to receive messages from Push Kit, you can call deleteToken() in
the HmsInstanceId class to delete the token of the app. After the deletion, the app will no longer
receive messages from Push Kit, including messages about subscribed topics.
You are advised not to use the deleteToken method. Instead, you can invalidate the token on your
app server, and configure your app server to send no message if the token is invalid. This avoids
frequent token requests.
private void deleteToken() {
// Create a thread.
new Thread() {
@Override
public void run() {
try {
// Obtain the app ID from the agconnect-service.json file.
String appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id");

// Enter the token ID HCM.


String tokenScope = "HCM";

// Delete the token.


HmsInstanceId.getInstance(context).deleteToken(appId, tokenScope);
Log.i(TAG, "token deleted successfully");
} catch (ApiException e) {
Log.e(TAG, "deleteToken failed." + e);
}
}
}.start();
}
When your app server executes topic-based messaging or sends data messages (including
notification messages that need to be processed by the app according to the function configuration
in Notification Message Display for App Running in the Foreground), you need to implement
the OnMessageRecieved() method for message receiving. Then your app processes the messages by
itself. @Override
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
Log.i(TAG, "getCollapseKey: " + message.getCollapseKey()
+ "\n getData: " + message.getData()
+ "\n getFrom: " + message.getFrom()
+ "\n getTo: " + message.getTo()
+ "\n getMessageId: " + message.getMessageId()
+ "\n getSendTime: " + message.getSentTime()
+ "\n getMessageType: " + message.getMessageType()
+ "\n getTtl: " + message.getTtl());

Toast.makeText(this , "recieved a data message "+message , Toast.LENGTH_LONG).show();


RemoteMessage.Notification notification = message.getNotification();
if (notification != null) {
Log.i(TAG, "\n getImageUrl: " + notification.getImageUrl()
+ "\n getTitle: " + notification.getTitle()
+ "\n getTitleLocalizationKey: " + notification.getTitleLocalizationKey()
+ "\n getTitleLocalizationArgs: " + Arrays.toString(notification.getTitleLocalizationArgs())
+ "\n getBody: " + notification.getBody()
+ "\n getColor: " + notification.getColor()
+ "\n getClickAction: " + notification.getClickAction()
+ "\n getChannelId: " + notification.getChannelId()
+ "\n getLink: " + notification.getLink()
+ "\n getNotifyId: " + notification.getNotifyId());
}
}
Notification messages are instant messages (IMs) that are directly displayed in the notification
panel. You can call the turnOnPush method in HmsMessaging to enable displaying notification
messages or call the turnOffPush method in HmsMessaging to disable displaying notification
messages. Displaying notification messages is enabled by default.

// Configure whether to display notification messages.


HmsMessaging.getInstance(context).turnOnPush().addOnCompleteListener(new
OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
// Obtain the result.
if (task.isSuccessful()) {
Log.i(TAG, "turnOnPush Complete");
} else {
Log.e(TAG, "turnOnPush failed: ret=" +
task.getException().getMessage());
}
}
});
HMS Core Push SDK 4.0 provides the capability of automatically generating AAIDs and
automatically applying for tokens. After this capability is configured, the token is returned through
the onNewToken() method. You can configure automatic initialization by adding the meta-
data section to the AndroidManifest.xml file or calling the setAutoInitEnabled(boolean enable)
method in HmsMessaging class.
• Method 1 :
Add the meta-data section in the AndroidManifest.xml file. The following is sample code, in
which the value of name is always push_kit_auto_init_enabled, and value indicates whether to
enable automatic initialization. The options are true (yes) and false (no).

<meta-data
android:name="push_kit_auto_init_enabled"
android:value="true"/>

• Method 2:
Explicitly call the setAutoInitEnabled (boolean enable) method in the MainActivity class. In the
method, the enable parameter indicates whether to enable automatic initialization. The
options are true (yes) and false (no).
The topic messaging function provided by Push Kit allows you to send messages to multiple
devices whose users have subscribed to a specific topic. You can write notification messages about
the topic as required, and Push Kit sends the messages to correct devices in a reliable manner.
For example, users of a weather forecast app can subscribe to the weather topic and receive
notification messages about weather.

To send messages by topic, complete the following process:


Subscribe to a topic for an app. This step can be performed on both the app and app server.
After subscribing to a topic, you can send messages based on the topic

The function in Push Kit has the following restrictions


A maximum of 2000 topics can be subscribed to for one app instance.
A maximum of 100 topic-based messages can be sent concurrently.
Use the subscribe method to subscribe to a topic. You can add a listener to check whether the
subscription task is successful.

public void subscribe(String topic) {


try {
// Subscribe to a topic.
HmsMessaging.getInstance(context).subscribe(topic)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
// Obtain the topic subscription result.
if (task.isSuccessful()) {
Log.i(TAG, "subscribe topic successfully");
} else {
Log.e(TAG, "subscribe topic failed, return value is " +
task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(TAG, "subscribe failed, catch exception : " + e.getMessage());
}
}
Use the unsubscribe method to subscribe to a topic. You can add a listener to check whether
the subscription task is successful.
public void unsubscribe(String topic) {
try {
// Unsubscribe from a topic.
HmsMessaging.getInstance(context).unsubscribe(topic)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
// Obtain the topic unsubscription result.
if (task.isSuccessful()) {
Log.i(TAG, "unsubscribe topic successfully");
} else {
Log.e(TAG, "subscribe topic failed, return value is " + task.getException().getMessage());
}
}
});
} catch (Exception e) {
Log.e(TAG, "subscribe failed, catch e
xception : " + e.getMessage());
}
}
04
Sign in to AppGalleryConnect select My projects, and find your project in the project list. Go
to Project settings > Grow > Push Kit > Notifications. Click Add notification to create a task.
You can view details about notification and data messages sent in charts and tables. In addition,
you can select AppGallery Connect, API, or All channels from the drop-down list box to filter the
details by channel.
 Sent times: Number of devices to which messages are sent.
 App uninstalled: Number of apps that are uninstalled and not reinstalled.
 Invalid token: Number of messages that are delivered to devices but not displayed due to an
invalid token (for example, the app is reinstalled but not activated, and a new token is not
synchronized).
 Rejected by users: Number of messages for which users have disabled the notification
permission on apps.
 Discarded for silent devices: Number of messages that devices do not receive because the devices
are not connected to the network for more than 30 days.
 Discarded due to frequency control: Number of messages that will be discarded when the
maximum number of messages sent based on a single token each day reaches 3,000.
 Cached: Number of messages that are still in a validity period even if receiving devices are
offline.
 Expired: Number of messages that expire because receiving devices are offline in a validity
period.
 Delivered times: Number of messages delivered to devices.
 Tapped times: Number of messages tapped by users.
 Delivery rate (%): Delivered times/Sent times.
 Tap-through rate (%): Tapped times/Delivered times.
You can view details about target users as well as statistics about active users, new users, and
total users by time.
FAQ
What is the maximum number of tokens for the Push Kit server to send messages at a time?
The Push Kit server allows a maximum of 1000 tokens for sending messages at a time. If more tokens need
to be used, your app server will have to send messages in batches.

What are the requirements for a phone to receive messages sent by the Push Kit server?
Device: A Huawei phone or a non-Huawei phone with HMS Core (APK) installed. The APK can be
downloaded from HUAWEI AppGallery.
Network: The phone is connected to the network and the connection is stable.
EMUI version: Some Huawei phones running EMUI 4.0 or EMUI 4.1 and all Huawei phones running EMUI
5.0 or a later version. EMUI 5.0 and later versions are recommended.

How can I check whether Push Kit is enabled for an app?


Sign in to AppGalleryConnect, select the project to be checked, go to Project settings > Manage APIs, and
check whether Push Kit is enabled.
Select My projects, and find your project in the project list. Go to Project settings > Grow > Push
Kit > Settings, and check whether Push Kit is enabled.
Some Useful Links

Official Document: https://developer.huawei.com/consumer/en/doc/development/HMS-


Guides/push-topic#h11576304009120

Push Kit Demo:


https://developer.huawei.com/consumer/en/codelab/HMSPushKit/index.html#0

Push Kit Article:


https://forums.developer.huawei.com/forumPortal/en/topic/0202326236067510002

https://forums.developer.huawei.com/forumPortal/en/topic/0201211024056890110

Youtube Link:
https://www.youtube.com/watch?v=U1gy7Tvfepc
Thank You

You might also like