/ SDKs / Android
Chat SDKs Android v4
Chat SDKs Android
Chat SDKs
Version 4

Set up push notifications for HMS

Copy link

The following is a set of step-by-step instructions on how to set up push notifications for HMS.

Note: See Push notifications for FCM if you want to learn how to set up notifications for FCM.

Step 1 Generate app ID and app secret for HMS

Copy link

The Sendbird server requires your app ID and app secret to send notification requests to HMS on behalf of your server. This is required for HMS to authorize HTTP requests.

Note: If you already have your app ID and app secret, skip this step and go directly to Step 2: Register app ID and app secret to Sendbird Dashboard.

  1. Go to the AppGallery Connect. If you don't have a project for a client app, create a new project.

  1. Select your project card to move to Project Settings.

  2. Go to Convention > App Information and copy your App ID and App secret to use them on Sendbird Dashboard later.

  1. During the registration process, enter your package name, download the agconnect-services.json file, and place it in your Android app module root directory.

Step 2 Register app ID and app secret to Sendbird Dashboard

Copy link

Register your app ID and app secret to the Sendbird server through the dashboard as follows.

  1. Sign in to your dashboard and go to Settings > Application > Push notifications.

  2. Turn on Push notifications and select Send when all devices are offline.

  3. Click Add credentials and register the app ID and app secret acquired at Step 1.

Step 3 Set up an HMS client app on your Android project

Copy link

Add the following dependency for the HUAWEI Push Kit Android library to your build.gradle files that are at the project level and app level.

Project levelApp level
allprojects {
    repositories {
            // ...
            maven { url 'https://developer.huawei.com/repo/' }

buildscript {
    repositories {
        // ...
        maven { url 'http://developer.huawei.com/repo/' }
    dependencies {
        // ...
        classpath 'com.huawei.agconnect:agcp:'

Note: To learn more about this step, refer to Huawei's Preparations guide. The Push Kit sample code for Android is another helpful reference.

Step 4 Register a registration token to the Sendbird server

Copy link

In order to send notification messages to a specific client app on an Android device, HMS requires an app instance's registration token which has been issued by the client app. Therefore, the Sendbird server also needs every registration token of client app instances to send notification requests to HMS on behalf of your server.

A user can have up to 20 HMS registration tokens. If a user who already has the maximum number of tokens attempts to add another one, the newest token replaces the oldest.

Upon the initialization of your app, the HMS SDK generates a unique, app-specific registration token for the client app instance on your user's device. HMS uses this registration token to determine which device to send notification messages to. After the HMS SDK has successfully generated the registration token, it is passed to the onNewToken() callback. Registration tokens must be registered to the Sendbird server by passing it as an argument to the parameter in the SendbirdChat.HMS.registerPushToken() method as in the following code.

override fun onNewToken(token: String) {
    SendbirdChat.HMS.registerPushToken(token) { status, e ->
        if (e != null) {
            // Handle error.

        if (status == PushTokenRegistrationStatus.PENDING) {
            // A token registration is pending.
            // Try registering again after a connection has been successfully established.

Note: If PushTokenRegistrationStatus.PENDING is returned through the handler, this means that your user isn't being connected to the Sendbird server when SendbirdChat.HMS.registerPushToken() is called. In this case, you must first get a pending registration token using getToken(), and then register the token by calling SendbirdChat.HMS.registerPushToken() in the onSuccess() callback when your user has been connected to the server.

SendbirdChat.connect(USER_ID) { user, e ->
    if (e != null) {
        // Handle error.

    thread {
        try {
            val appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id")
            val token = HmsInstanceId.getInstance(context).getToken(appId, "HCM")
            SendbirdChat.HMS.registerPushToken(token) { status, e ->
                if (e != null) {
                    // Handle error.

                // ...
        } catch (e: Exception) {}

When the server fails to return a token after a client app has called the getToken() method, it tries to return the token through the onNewToken() method instead as in the following scenario.

  1. After the server has failed to return a token, HUAWEI Push Kit automatically calls the method again, then the server returns the requested token through the onNewToken() method.

  2. If the requested token has expired, the server returns the updated token through the onNewToken() method.

  3. When the EMUI version of a Huawei device is lower than 10.0, the server returns the token through the onNewToken() method.

Step 5 Handle an HMS message payload

Copy link

The Sendbird server sends push notification payloads as HMS notification messages, which contain notification-related data in the form of key-value pairs. Unlike notification messages, the client app needs to parse and process these data messages in order to display them as local notifications.

The following code shows how to receive a push notification payload and parse it as a local notification. The payload consists of two properties: message and sendbird. The message property is a string generated according to a push notification template you set on the Sendbird Dashboard. The sendbird property is a JSON object which contains all the information about the message a user has sent. Within MyFirebaseMessagingService.java, you can show the parsed messages to users as a notification using your custom sendNotification() method.

Note: See Huawei’s Receive messages in an Android app guide to learn more about how to implement code to receive and parse an HMS notification message, how notification messages are handled depending on the state of the receiving app, how to edit the app manifest, and how to override the onMessageReceived() method.

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    try {
        if (remoteMessage.getDataOfMap().containsKey("sendbird")) {
            val sendbird = JSONObject(remoteMessage.getDataOfMap().get("sendbird"))
            val channel = sendbird.get("channel") as JSONObject
            val channelUrl = channel["channel_url"] as String
            val messageTitle = sendbird.get("push_title") as String
            val messageBody = sendbird.get("message") as String
            // If you want to customize a notification with the received HMS message,
            // write your method like sendNotification() below.
            sendNotification(context, messageTitle, messageBody, channelUrl)
    } catch (e: JSONException) {
// ...

fun sendNotification(
    context: Context,
    messageTitle: String,
    messageBody: String,
    channelUrl: String
) {
    // Implement your own way to create and show a notification containing the received HMS message.
    val notificationBuilder = NotificationCompat.Builder(context, channelUrl)
        .setColor(Color.parseColor("#7469C4")) // small icon background color
        .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.logo_sendbird))

The following is a complete payload format of the sendbird property, which contains a set of provided key-value items. Some fields in the push notification payload can be customized in Settings > Chat > Notifications on the Sendbird Dashboard. For example, push_title and push_alert are created based on the Title and Body text you set in Push notification content templates, respectively, in the Push notifications menu. In order to display them in a local notification, pass push_title and push_alert of the push notification payload into the setContentTitle and setContentText methods of the NotificationCompat.Builder class, respectively. Also, the channel_unread_count field can be added into or removed from the payload in the same menu on the Sendbird Dashboard.

    "category": "messaging:offline_notification",
    "type": string,                         // Message type: MESG, FILE, or ADMM
    "message": string,                          // User input message
    "custom_type": string,                  // Custom message type
    "message_id": long,                      // Message ID
    "created_at": long,                      // The time that the message was created, in a 13-digit Unix milliseconds format
    "app_id": string,                            // Application's unique ID
    "unread_message_count": int,        // Total number of new messages unread by the user
    "channel": {
        "channel_url": string,          // Group channel URL
        "name": string,                      // Group channel name
        "custom_type": string,           // Custom Group channel type
        "channel_unread_count": int // Total number of unread new messages from the specific channel
    "channel_type": string,             // A value of channel_type is set by the system. The value of messaging indicates a distinct group channel while group_messaging indicates a private group channel and chat indicates all other cases.
    "sender": {
        "id": string,                            // Sender's unique ID
        "name": string,                      // Sender's nickname
        "profile_url": string,           // Sender's profile image URL
        "require_auth_for_profile_image": false,
        "metadata": {}
    "recipient": {
        "id": string,                            // Recipient's unique ID
        "name": string                          // Recipient's nickname
    "files": [],                            // An array of data regarding the file message, such as filename
    "translations": {},                      // The items of locale:translation.
    "push_title": string,           // Title of a notification message that can be customized in the Sendbird Dashboard with or without variables
    "push_alert": string,           // Body text of a notification message that can be customized in the Sendbird Dashboard with or without variables
    "push_sound": string,           // The location of a sound file for notifications
    "audience_type": string,                // The type of audiences for notifications
    "mentioned_users": {
        "user_id": string,              // The ID of a mentioned user
        "nickname": string,         // The nickname of a mentioned user
        "profile_url": string,      // Mentioned user's profile image URL
        "require_auth_for_profile_image": false