Chat SDKs Android v3
Chat SDKs Android
Chat SDKs
Android
Version 3
Sendbird Chat SDK v3 for Android is no longer supported as a new version is released. Check out our latest Chat SDK v4

Push notifications

Copy link

A push notification is a message that is immediately delivered to a user's device when the device is either idle or running the client app in the background. Push notifications for Android client apps are sent using Firebase Cloud Messaging (FCM) or Huawei Mobile Service (HMS), which contains custom data that your app needs in order to respond to the notifications. When a message is sent to Sendbird server through our Chat SDK for Android, the server communicates with FCM or HMS, and then they deliver a push notification to an Android device where the client app is installed.

Note: By default, when a user's device is disconnected from Sendbird server, the server sends push notification requests to FCM for the messages. The Chat SDK for Android automatically detects when a user's client app goes into the background from the foreground, and updates the user's connection status to disconnected. Therefore, under normal circumstances, you don't need to explicitly call the disconnect() method.

Notifications can also be configured to display an alert, play a sound, or badge your app’s icon and are only applicable to group channels. They can't be applied to an open channel or a supergroup channel due to the massive number of users and messages.

Push notifications support both single and multi-device users and they are delivered only when a user is fully offline from all devices even when they use only one device. In other words, if a user is online on one or more devices, notifications aren't delivered and thus not displayed on any devices.

Sendbird provides two options for push notifications. Choose an appropriate option upon consideration of how much support for multi-device push notifications the client app requires. Push notifications with Multi-Device support deliver notifications to all offline devices even when a user is online on one or more devices. Refer to Understanding the differences in the Multi-Device Support page to learn more about the difference between the two options in detail.


Push notifications for FCM

Copy link

There are two types of FCM messages: notification messages and data messages. Sendbird uses data messages, which are handled by the client app. They allow users to customize the message payload, which consists of key-value items.

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

Note: Move to Push notifications for HMS if you want to see the instructions for HMS push notifications.

Step 1: Generate server key for FCM

Copy link

Sendbird server requires your server key to send notification requests to FCM on behalf of your server. This is required for FCM to authorize HTTP requests.

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

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

  1. Select your project card to move to the Project Overview.

  2. Click the gear icon at the upper left corner and select Project settings.

  1. Go to Cloud Messaging > Project credentials and copy your server key.

Note: If a server key wasn't generated because the Cloud Messaging API is disabled by default, see how to enable the legacy API.

  1. Go to the General tab and select your Android app to add Firebase to. During the registration process, enter your package name, download the google-services.json file, and place it in your Android app module root directory.

Step 2: Register server key to Sendbird Dashboard

Copy link

Register your server key to Sendbird server through the dashboard as follows:

  1. Sign in to your dashboard and go to Settings > Chat > Notifications.
  2. Turn on Notifications and select the Send when all devices are offline option.
  3. Click the Add credentials button and register the app ID and app secret acquired at Step 1.

Note: Your server key can also be registered using our Chat Platform API's add an FCM push configuration action.

Step 3: Set up an FCM client app on your Android project

Copy link

Add the following dependency for the Cloud Messaging Android library to your build.gradle file as below:

Note: The firebase-messaging version should be 19.0.1 or higher.

dependencies {
    ...

    implementation 'com.google.firebase:firebase-messaging:20.1.0'
}

Note: To learn more about this step, refer to Firebase's Set Up a Firebase Cloud Messaging client app on Android guide. The Google FCM sample project is another helpful reference.

Step 4: Register a registration token to Sendbird server

Copy link

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

Note: A user can have up to 20 FCM registration tokens. If a user who already has the maximum number of tokens adds another one, the newest token will push out the oldest, meaning the oldest token will be deleted to add the newest.

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

@Override
public void onNewToken(String token) {
    ...

    // Register a registration token to Sendbird server.
    SendBird.registerPushTokenForCurrentUser(token, new SendBird.RegisterPushTokenWithStatusHandler() {
        @Override
        public void onRegistered(SendBird.PushTokenRegistrationStatus ptrs, SendBirdException e) {
            if (e != null) {
                // Handle error.
            }

            if (ptrs == SendBird.PushTokenRegistrationStatus.PENDING) {
                // A token registration is pending.
                // Retry the registration after a connection has been successfully established.
            }
        }
    });
}

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

SendBird.connect(USER_ID, new SendBird.ConnectHandler() {
    @Override
    public void onConnected(User user, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MyActivity.this, new OnSuccessListener<InstanceIdResult>() {
            @Override
            public void onSuccess(InstanceIdResult instanceIdResult) {
                SendBird.registerPushTokenForCurrentUser(instanceIdResult.getToken(), new SendBird.RegisterPushTokenWithStatusHandler() {
                    @Override
                    public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                        if (e != null) {
                            // Handle error.
                        }

                        ...
                    }
                });
            }
        });
    }
}

Step 5: Handle an FCM message payload

Copy link

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

The following code shows how to receive a Sendbird’s 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 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 the MyFirebaseMessagingService.java, you can show the parsed messages to users as a notification by using your custom sendNotification() method.

Note: Visit Firebase’s Receive messages in an Android app guide to learn more about how to implement codes to receive and parse a FCM notification message, how notification messages are handled depending on the state of the receiving app, how to edit the app manifest, or how to override the onMessageReceived method.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String channelUrl = null;
    try {
        if (remoteMessage.getData().containsKey("sendbird")) {
            JSONObject sendbird = new JSONObject(remoteMessage.getData().get("sendbird"));
            JSONObject channel = (JSONObject) sendbird.get("channel");
            channelUrl = (String) channel.get("channel_url");
            messageTitle = (String) sendbird.get("push_title");
            messageBody = (String) sendbird.get("message");

            // If you want to customize a notification with the received FCM message,
            // write your method like the sendNotification() below.
            sendNotification(context, messageTitle, messageBody, channelUrl);
         }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
...

public static void sendNotification(Context context, String messageTitle, String messageBody, String channelUrl) {
    // Implement your own way to create and show a notification containing the received FCM message.
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(context, channelUrl)
            .setSmallIcon(R.drawable.img_notification)
            .setColor(Color.parseColor("#7469C4"))  // small icon background color
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo_sendbird))
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(pendingIntent);

    ...
}

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, the push_title and push_alert are created based on the Title and Body text you set in Push notification content templates, respectively, in the Notifications menu. In order to display them in a local notification, pass the push_title and push_alert of the push notification payload into the setContentTitle and setContentText method 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,         // The value of "channel_type" is set by the system. The '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_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
    },
}

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: Move to Push notifications for FCM if you want to see the instructions for FCM push notifications.

Step 1: Generate app ID and app secret for HMS

Copy link

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.
  2. Select your project card to move to the Project Settings.
  3. Go to Convention > App Information and copy your App ID and App secret to use them in your Sendbird Dashboard later.
  4. 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 Sendbird server through the dashboard as follows:

  1. Sign in to your dashboard and go to Settings > Chat > Notifications.
  2. Turn on Notifications and select Send when all devices are offline.
  3. Click the Add credentials button 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 yourbuild.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:1.1.1.300'
    }
}

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 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, Sendbird server also needs every registration token of client app instances to send notification requests to HMS on behalf of your server.

Note: A user can have up to 20 HMS registration tokens. If a user who already has the maximum number of tokens adds another one, the newest token will push out the oldest, meaning the oldest token will be deleted to add the newest.

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 successfully generates the registration token, it is passed to the onNewToken() callback. Registration tokens must be registered to Sendbird server by passing it as an argument to the parameter in the SendBird.HMS.registerPushTokenForCurrentUser() method as shown below.

@Override
public void onNewToken(String token) {
    // ...

    // Register a registration token to Sendbird server.
    SendBird.HMS.registerPushTokenForCurrentUser(token, new SendBird.RegisterPushTokenWithStatusHandler() {
        @Override
        public void onRegistered(SendBird.PushTokenRegistrationStatus ptrs, SendBirdException e) {
            if (e != null) {
                // Handle error.
            }

            if (ptrs == SendBird.PushTokenRegistrationStatus.PENDING) {
                // A token registration is pending.
                // Retry the registration after a connection has been successfully established.
            }
        }
    });
}

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

SendBird.connect(USER_ID, new SendBird.ConnectHandler() {
    @Override
    public void onConnected(User user, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id");
                    String token = HmsInstanceId.getInstance(context).getToken(appId, "HCM");
                    SendBird.HMS.registerPushTokenForCurrentUser(token, new SendBird.RegisterPushTokenWithStatusHandler() {
                        @Override
                        public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                            if (e != null) {
                                // Handle error.
                            }

                            ...
                        }
                    });
                } catch (Exception e) {
                    Log.i(TAG, "getToken failed.");
                }
            }
        }).start();
    }
});

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

  1. After the server 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 is 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

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 those data messages in order to display them as local notifications.

The following code shows how to receive a Sendbird’s 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 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 the MyFirebaseMessagingService.java, you can show the parsed messages to users as a notification by using your custom sendNotification() method.

Note: Visit 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
public void onMessageReceived(RemoteMessage remoteMessage) {
    String channelUrl = null;
    try {
        if (remoteMessage.getDataOfMap().containsKey("sendbird")) {
            JSONObject sendbird = new JSONObject(remoteMessage.getDataOfMap().get("sendbird"));
            JSONObject channel = (JSONObject) sendbird.get("channel");
            channelUrl = (String) channel.get("channel_url");
            messageTitle = (String) sendbird.get("push_title");
            messageBody = (String) sendbird.get("message");

            // To customize a notification with the received HMS message,
            // write your method like the sendNotification() below.
            sendNotification(context, messageTitle, messageBody, channelUrl);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

...

public static void sendNotification(Context context, String messageTitle, String messageBody, String channelUrl) {
    // Implement your own way to create and show a notification containing the received HMS message.
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(context, channelUrl)
            .setSmallIcon(R.drawable.img_notification)
            .setColor(Color.parseColor("#7469C4"))  // small icon background color
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo_sendbird))
            .setContentTitle(messageTitle)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentIntent(pendingIntent);
}

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, the push_title and push_alert are created based on the Title and Body text you set in Push notification content templates, respectively, in the Notifications menu. In order to display them in a local notification, pass the push_title and push_alert of the push notification payload into the setContentTitle and setContentText method 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,         // The value of "channel_type" is set by the system. The '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
    },
}

Notification preferences

Copy link

By registering or unregistering the current user's registration token to Sendbird server as below, you can turn push notifications on or off in the user's client app.

Note: The registration and unregistration methods in the code below should be called after a user has established a connection with Sendbird server by calling the SendBird.connect() method.

FCMHMS
public void setPushNotification(boolean enable) {
    if (enable) {
        SendBird.registerPushTokenForCurrentUser(pushToken, new SendBird.RegisterPushTokenWithStatusHandler() {
            @Override
            public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                if (e != null) {
                    // Handle error.
                }

                ...
            }
        });
    }
    else {
        // If you want to unregister the current device only, call this method.
        SendBird.unregisterPushTokenForCurrentUser(pushToken, new SendBird.UnregisterPushTokenHandler() {
            @Override
            public void onUnregistered(SendBirdException e) {
                if (e != null) {
                    // Handle error.
                }

                ...
            }
        });

        // If you want to unregister all devices of the user, call this method.
        SendBird.unregisterPushTokenAllForCurrentUser(new SendBird.UnregisterPushTokenHandler() {
            @Override
            public void onUnregistered(SendBirdException e) {
                if (e != null) {
                    // Handle error.
                }

                ...
            }
        });
    }
}

The SendBird.PushTriggerOption allows users to configure when to receive notification messages as well as what type of messages will trigger notification messages. This provides the following three options:

OptionDescription

ALL

When disconnected from Sendbird server, the current user receives notifications for all new messages including messages the user has been mentioned in.

MENTION_ONLY

When disconnected from Sendbird server, the current user only receives notifications for messages the user has been mentioned in.

OFF

The current user doesn't receive any notifications.

FCMHMS
// If you want to trigger notification messages only when the current user is mentioned in messages.
SendBird.setPushTriggerOption(SendBird.PushTriggerOption.MENTION_ONLY, new SendBird.SetPushTriggerOptionHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
}

The GroupChannel.PushTriggerOption also allows users to configure the trigger for notification messages as well as turn notifications on or off for each channel. This provides the following four options:

List of push trigger options

Copy link
OptionDescription

DEFAULT

The current user’s push notification trigger settings are automatically applied to the channel. This is the default setting.

ALL

When disconnected from Sendbird server, the current user receives notifications for all new messages in the channel including messages the user has been mentioned in.

MENTION_ONLY

When disconnected from Sendbird server, the current user only receives notifications for messages in the channel the user has been mentioned in.

OFF

The current user doesn't receive any notifications in the channel.

FCMHMS
// If you want to automatically apply the user's push notification settings to the channel.
groupChannel.setMyPushTriggerOption(GroupChannel.PushTriggerOption.DEFAULT, new GroupChannel.GroupChannelSetMyPushTriggerOptionHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

If you want to routinely turn off push notification on the current user's client app according to a specified schedule, use our Do Not Disturb feature like the following.

Note: Do Not Disturb can also be set for a user with our Chat Platform API's update push notification preferences action.

FCMHMS
// The current user will not receive notification messages during the specified time of every day.
SendBird.setDoNotDisturb(true, START_HOUR, START_MIN, END_HOUR, END_MIN, TimeZone.getDefault().getID(), new SendBird.SetDoNotDisturbHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

To snooze notification messages for a specific period of time, use our snooze feature as below.

Note: snooze notifications can also be set for a user with our Chat Platform API's update push notification preferences action.

FCMHMS
// The current user will not receive notification messages during the specified period of time (from START_TS to END_TS).
SendBird.setSnoozePeriod(true, START_TS, END_TS, new SendBird.SetSnoozePeriodHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

Push notification content templates

Copy link

Push notification content templates are pre-formatted forms that can be customized to display your own push notification messages on a user’s device. Sendbird provides two types: default and alternative. Both templates can be customized from your dashboard by going to Settings > Chat > Notifications > Push notification content templates.

As for Android, an additional implementation is required in order to display your customized push notifications. The push notification payload sent from Sendbird server will include content of the template, such as the title and message, and the client app can determine how to present the notification through codes provided by Android. For more information on how to create a custom notification, refer to Notifications at Android's Documentation for app developers.

Huawei Mobile Service (HMS) also requires an additional implementation for custom push notifications. To learn more, see Push Kit at Huawei's Documentation.

Content templates

Copy link

There are two types of push notification content template: Default and Alternative. Default template is a template that applies to users with the initial notification message setting. Alternative template is used when a user selects a different notification content template instead of the default template.

The content in the template is set at the application level while the selection of templates is determined by a user or through the Platform API.

Note: When a custom channel type has its own customized push notification content template, it takes precedence over the default or alternative templates.

Both templates can be customized using the variables of sender_name, filename, message, channel_name, and file_type_friendly which will be replaced with the corresponding string values. As for the file_type_friendly, it will indicate the type of the file sent, such as Audio, Image, ans Video.

List of content templates

Copy link

Refer to the following table for the usage of content templates:

Text messageFile message

Default template

{sender_name}: {message} (ex. Cindy: Hi!)

{filename} (ex. hello_world.jpg)

Alternative template

New message arrived

New file arrived

To apply a template to push notifications, use the setPushTemplate() method. Specify the type of the template with the name as either SendBird.PUSH_TEMPLATE_DEFAULT or SendBird.PUSH_TEMPLATE_ALTERNATIVE.

FCMHMS
SendBird.setPushTemplate(SendBird.PUSH_TEMPLATE_ALTERNATIVE, new SendBird.SetPushTemplateHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // Push template successfully set to 'SendBird.PUSH_TEMPLATE_ALTERNATIVE'.
    }
});

To check the current user's push notification template, use the getPushTemplate() method as follows:

FCMHMS
SendBird.getPushTemplate(new SendBird.GetPushTemplateHandler() {
    @Override
    public void onResult(String s, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        if (s.equals(SendBird.PUSH_TEMPLATE_DEFAULT)) {
            // Currently configured to use the default template.
        } else if (s.equals(SendBird.PUSH_TEMPLATE_ALTERNATIVE)) {
            // Currently configured to use the alternative template.
        }
    }
});

Push notification tester

Copy link

After registering a credential for push notification services, you can test whether push notification credentials and notification services work properly through the Sendbird Dashboard.

In Settings > Notifications > Push notification credentials on the dashboard, each credential has a Send button that allows you to send a test message. The test message will be sent to a target user and their device, which sets off a push notification on the device. At the same time, a new group channel will be created for this test, containing only the target user. If you've already tested push notification with the same target user and the same target device token, the message will be sent to the existing test channel.

Note: If there is another member in the test channel or the target user has left the channel, delete the test channel before carrying out a test.

  1. Go to Settings > Notifications > Push notification credentials on Sendbird Dashboard. Find a Send button in the right-end column of each table.

  1. You can search a target user by either their User ID or Nickname in the popup window. Once a user is selected, choose a target device from a list of device tokens linked to the user.

  1. Double check to see if you've selected a correct device token of the user because this push notification will show up on an actual device. Confirm the target channel name and URL, then send the message.

Note: If this is your first test, a new test channel will be created. For future tests with the same target user and the same target device token, the name and URL of the existing test channel will show above the message box.

  1. Check to see if the push notification arrived on the mobile device or emulator. The test message will state the time when Sendbird server sent the message.
Test message sent at {HH:MM:SS} on {MM-DD-YYYY}

Note: In order to display push notifications on Android devices and emulators, an additional implementation is required in the client app. To learn more, see Push notification for FCM or Push notification for HMS.


Push notification translation

Copy link

Push notification translation allows your users to receive notification messages in their preferred languages. Users can set up to four preferred languages. If messages are sent in one of those languages, the notification messages won’t be translated. If messages are sent in a language other than the preferred languages, the notification messages will be translated into the user's first preferred language. In addition, the messages translated into other preferred languages will be provided in the sendbird property of a notification message payload.

Note: A specific user's preferred languages can be set with our Chat Platform API's update a user action.

The following shows how to set the current user's preferred languages using the updateCurrentUserInfo() method:

List<String> preferredLanguages = new ArrayList<>();
preferredLanguages.add("fr");   // French
preferredLanguages.add("de");   // German
preferredLanguages.add("es");   // Spanish
preferredLanguages.add("ko");   // Korean

SendBird.updateCurrentUserInfo(preferredLanguages, new SendBird.UserInfoUpdateHandler() {
    @Override
    public void onUpdated(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        boolean isUpdatedSuccessfully = true;

        for (String language : SendBird.getCurrentUser().getPreferredLanguages()) { // The getPreferredLanguages() returns a list of the current user's preferred languages.
            if(!preferredLanguages.contains(language)) {
                isUpdatedSuccessfully = false;
                break;
            }
        }

        if (isUpdatedSuccessfully) {
            // The current user's preferred languages have been updated successfully.
        }
    }
});

If successful, the following notification message payload will be delivered to the current user's device.

{
    "message": {
        "token": "ad3nNwPe3H0:ZI3k_HHwgRpoDKCIZvvRMExUdFQ3P1...",
        "notification": {
            "title": "Greeting!",
            "body": "Bonjour comment allez vous"    // A notification message is translated into the first language listed in the preferred languages.
        },
        ...

    },
    "sendbird": {
        "category": "messaging:offline_notification",
        "type": "User",
        "message": "Hello, how are you?",
        ...

        "translations": {   // The translated messages in other preferred languages.
            "fr": "Bonjour comment allez vous",
            "de": "Hallo wie geht es dir",
            "es": "Hola como estas"
        },
        ...

    }
}

Enable Cloud Messaging API

Copy link

To enable the legacy Cloud Messaging API, take the following steps.

Step 1 Open Firebase console

Copy link

In the Firebase console, go to Project settings > Cloud Messaging and select Manage API in Google Cloud Console to open Google Cloud Console.

Step 2 Go to API Library

Copy link

Move to API Library by using the back button as shown below.

Step 3 Find Cloud Messaging API

Copy link

In the search bar, type "cloud messaging."

In the search results, select Cloud Messaging as shown below.

Step 4 Enable Cloud Messaging API

Copy link

Click the Enable button to start using the Cloud Messaging API.

Step 5 Check that the legacy API is enabled

Copy link

If you go back to your Firebase console, the Cloud Messaging API should be enabled with a newly generated server key.