Android
Push Notifications

Push Notifications for Android

A push notification is a message that is immediately delivered to a user device when the device is either idle or running your client app in the background. Push notifications for Android client apps are sent using Firebase Cloud Messaging (FCM) or Huawei Mobile Service (HMS) and include custom data your app needs 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 your 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 super group 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 your client app requires. Compared to this general push notification option, with Multi-Device support, push notifications are delivered 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 understand the differences between two options in detail.


Push notifications for FCM

This part covers the following step-by-step instructions of our 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

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 your client app, create a new project.
    Project detail
  2. Select your project card to move to the Project Overview.
  3. Click the gear icon at the upper left corner and select Project settings.
    Project settings
  4. Go to Cloud Messaging > Project credentials and copy your server key.
    Server key
  5. 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. Add firebase to Android App

Step 2: Register server key to Sendbird Dashboard

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

  1. Sign in to your dashboard and go to Settings > Application > 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. Set Push Information

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

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

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

build.gradle
Light Color Skin
Copy
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

Note: A user can have up to 20 newest FCM registration tokens. If a new token is added to a user who already has a maximum number of tokens, the newest pushes the oldest out, which means the oldest token will be deleted when a new one is added.

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 your client app instances to send notification requests to FCM on behalf of your server.

When the FCM SDK successfully generates a registration token upon initial startup of your app, this token is passed to the onNewToken() callback. Registration tokens must be registered to Sendbird server by passing it as an argument to a parameter in the registerPushTokenForCurrentUser() method as shown below.

Note: Upon initial startup of your app, the FCM SDK generates a unique and 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.

MyFirebaseMessagingService.java
Light Color Skin
Copy
@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) {
                return;
            }

            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.

Light Color Skin
Copy
SendBird.connect(USER_ID, new SendBird.ConnectHandler() {
    @Override
    public void onConnected(User user, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }   

        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) {        // Error.
                            return;
                        }
                    }
                });
            }
        });
    }
}

Step 5: Handle an FCM message payload

To learn more about how to implement code 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, refer to Firebase's Receive messages in an Android app guide.

The following code shows how to receive and parse a notification message payload which consists of two properties: message and sendbird. The message property is a string generated according to a chosen notification template. 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 notifications by using your custom sendNotification() method.

MyFirebaseMessagingService.java
Light Color Skin
Copy
@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");

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

public static void sendNotification(Context context, String messageBody, String channelUrl) {
    // TODO: Implement your own way to create and show a notification containing the received FCM message.
}

The following is a complete payload format of the sendbird property, which contains a set of provided key-value items.

Light Color Skin
Copy
{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type: 'User', 'File', or 'Admin'
    "message": string,              // User input message
    "data": string,                 // Custom data field
    "custom_type": string,          // Custom message type
    "message_id": long,             // Message ID
    "created_at": long,             // 13-digit timestamp
    "app_id": string,               // Application's unique ID
    "unread_message_count": int,    // Total unread count of the user
    "channel": {
        "channel_url": string,      // Group channel URL
        "name": string,             // Group channel name
        "custom_type": string       // Group channel custom_type
    },
    "channel_type": string,         // Channel type: 'messaging', 'group_messaging', or 'chat'
    "sender": {
        "id": string,               // Sender's unique ID
        "name": string,             // Sender's nickname
        "profile_url": string       // Sender's profile image URL 
    },
    "recipient": {
        "id": string,               // Recipient's unique ID
        "name": string              // Recipient's nickname
    },
    "files": [],                    // If a message is a file link, this array represents files
    "translations": {},             // If a message has translations, this dict has locale:translation.
    "push_alert": string,           // A customized alert push notification 
    "push_sound": string,           // The location of a sound file for notification messages
    "audience_type": string,        // The type of audiences to receive notification messages
    "mentioned_users": {
        "user_id": string,                      // The ID of a mentioned user 
        "total_unread_mention_count": int,      // The number of messages which a user has been mentioned but has not read within the channels 
        "channel_unread_mention_count": int,    // The number of channels with messages which a user has been mentioned but has not read
        "is_hidden": boolean                    // Whether or not a mentioned user has hidden the channel from the list
    } 
}

Push notifications for HMS

This part covers the following step-by-step instructions of our 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

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 your client app, create a new project.
    Project detail
  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.
    Project settings
  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.
    Server key

Step 2: Register app ID and app secret to Sendbird Dashboard

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 > Application > 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. Server key

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

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 level
App level
Light Color Skin
Copy
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'
    }
}
Light Color Skin
Copy
apply plugin: 'com.huawei.agconnect'
...

dependencies {
    // Retain other existing dependencies.
    ...
    // Replace {version} with the actual SDK version number, for example, implementation 'com.huawei.hms:push:4.0.3.301'.
    implementation 'com.huawei.hms:push:{version}'
}

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

Note: A user can have up to 20 newest HMS registration tokens. If a new token is added to a user who already has a maximum number of tokens, the newest pushes the oldest out, which means the oldest token will be deleted when a new one is added.

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 your client app instances to send notification requests to HMS on behalf of your server.

When the HMS SDK successfully generates a registration token upon initial startup of your app, this token is passed to the onNewToken() callback. Registration tokens must be registered to Sendbird server by passing it as an argument to a parameter in the SendBird.HMS.registerPushTokenForCurrentUser() method as shown below.

Note: Upon initial startup of your app, the HMS SDK generates a unique and 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.

Light Color Skin
Copy
@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) {
                return;
            }

            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.

Light Color Skin
Copy
SendBird.connect(USER_ID, new SendBird.ConnectHandler() {
    @Override
    public void onConnected(User user, SendBirdException e) {
        if (e != null) {  // Error.
            return;
        }

        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) {        // Error.
                                return;
                            }
                        }
                    });
                } 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

To learn more about how to implement code to receive and parse a HMS 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, refer to Huawei's Receive messages in an Android app guide.

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

Light Color Skin
Copy
@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");

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

...

public static void sendNotification(Context context, String messageBody, String channelUrl) {
    // TODO: Implement your own way to create and show a notification containing the received HMS message.
}

The following is a complete payload format of the sendbird property, which contains a set of provided key-value items.

Light Color Skin
Copy
{
    "category": "messaging:offline_notification",
    "type": string,          // Message type: 'User', 'File', or 'Admin'
    "message": string,              // User input message
    "data": string,                 // Custom data field
    "custom_type": string,          // Custom message type
    "message_id": long,             // Message ID
    "created_at": long,             // 13-digit timestamp
    "app_id": string,               // Application's unique ID
    "unread_message_count": int,    // Total unread count of the user
    "channel": {
        "channel_url": string,      // Group channel URL
        "name": string,             // Group channel name
        "custom_type": string       // Group channel custom_type
    },
    "channel_type": string,      // 'messaging', 'group_messaging', or 'chat'
    "sender": {
        "id": string,               // Sender's unique ID
        "name": string,             // Sender's nickname
        "profile_url": string       // Sender's profile image URL 
    },
    "recipient": {
        "id": string,               // Recipient's unique ID
        "name": string              // Recipient's nickname
    },
    "files": [],      // If a message is a file link, this indicates files
    "translations": {},             // The items of locale:translation.
    "push_alert": string,           // A customized alert push notification 
    "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 
        "total_unread_mention_count": int,      // The number of messages which a user has been mentioned but has not read within the channels 
        "channel_unread_mention_count": int,    // The number of channels with messages which a user has been mentioned but has not read
        "is_hidden": boolean                    // Whether or not a mentioned user has hidden the channel from the list
    } 
}

Notification preferences

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.

FCM
HMS
Light Color Skin
Copy
public void setPushNotification(boolean enable) {
    if (enable) {
        SendBird.registerPushTokenForCurrentUser(gcmRegToken,
            new SendBird.RegisterPushTokenWithStatusHandler() {
                @Override
                public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                    if (e != null) {    // Error.
                        return;
                    }
                }
            }
        );
    }
    else {
        // If you want to unregister the current device only, call this method.
        SendBird.unregisterPushTokenForCurrentUser(gcmRegToken,
            new SendBird.UnregisterPushTokenHandler() {
                @Override
                public void onUnregistered(SendBirdException e) {
                    if (e != null) {    // Error.
                        return;
                    }
                }
            }
        );

        // 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) {    // Error.
                    return;
                }
            }
        });
    }        
}
Light Color Skin
Copy
public void setPushNotification(boolean enable) {
    if (enable) {
        SendBird.HMS.registerPushTokenForCurrentUser(hmsRegToken,
        new SendBird.RegisterPushTokenWithStatusHandler() {
                @Override
                public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                    if (e != null) {   // Error.
                        return;
                    }
                }
            }
        );
    }
    else {
        // If you want to unregister the current device only, call this method.
        SendBird.HMS.unregisterPushTokenForCurrentUser(hmsRegToken,
            new SendBird.UnregisterPushTokenHandler() {
                @Override
                public void onUnregistered(SendBirdException e) {
                    if (e != null) {    // Error.
                        return;
                    }
                }
            }
        );

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

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.

FCM
HMS
Light Color Skin
Copy
// 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) {    // Error.
            return;
        }
    }
} 
Light Color Skin
Copy
// If you want to trigger notification messages only when the current user is mentioned in messages.
SendBird.HMS.setPushTriggerOption(SendBird.PushTriggerOption.MENTION_ONLY, new SendBird.SetPushTriggerOptionHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
} 

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:

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.

FCM
HMS
Light Color Skin
Copy
// 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) {    // Error.
            return;
        }

        // If you want to turn off notification messages for this channel, pass `false` as an argument to a parameter. By default, they are turned on for a channel (true). 
        groupChannel.setPushPreference(false, new GroupChannel.GroupChannelSetPushPreferenceHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {    // Error.
                    return;
                }
            }
        });
    }
});
Light Color Skin
Copy
// 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) {    // Error.
            return;
        }

        // If you want to turn off notification messages for this channel, pass `false` as an argument to a parameter. By default, they are turned on for a channel (true).
        groupChannel.setPushPreference(false, new GroupChannel.GroupChannelSetPushPreferenceHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {    // Error.
                    return;
                }
            }
        });
    }
});

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 preferences action.

FCM
HMS
Light Color Skin
Copy
// 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) {    // Error.
            return;
        }
    }
});
Light Color Skin
Copy
// The current user will not receive notification messages during the specified time of every day.
SendBird.HMS.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) {    // Error.
            return;
        }
    }
});

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 preferences action.

FCM
HMS
Light Color Skin
Copy
// 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) {    // Error.
            return;
        }
    }
});
Light Color Skin
Copy
// The current user will not receive notification messages during the specified period of time (from START_TS to END_TS).
SendBird.HMS.setSnoozePeriod(true, START_TS, END_TS, new SendBird.SetSnoozePeriodHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

Push notification content templates

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 > Application > Notifications > Push notification content templates.

Content templates

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 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}, and {channel_name}, which represent the corresponding string values.

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.

FCM
HMS
Light Color Skin
Copy
SendBird.setPushTemplate(SendBird.PUSH_TEMPLATE_ALTERNATIVE, new SendBird.SetPushTemplateHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
        }
        // Push template successfully set to SendBird.PUSH_TEMPLATE_ALTERNATIVE.
    }
});
Light Color Skin
Copy
SendBird.HMS.setPushTemplate(SendBird.PUSH_TEMPLATE_ALTERNATIVE, new SendBird.SetPushTemplateHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
        }
            // The template successfully set to SendBird.PUSH_TEMPLATE_ALTERNATIVE.
    }
});

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

FCM
HMS
Light Color Skin
Copy
SendBird.getPushTemplate(new SendBird.GetPushTemplateHandler() {
    @Override
    public void onResult(String s, SendBirdException e) {
        if (e != null) {    // 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.
        }
    }
});
Light Color Skin
Copy
SendBird.HMS.getPushTemplate(new SendBird.GetPushTemplateHandler() {
    @Override
    public void onResult(String s, SendBirdException e) {
        if (e != null) {    // 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 translation

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:

Light Color Skin
Copy
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) {    // 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.

Light Color Skin
Copy
{
    "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",
            "kr": "안녕하십니까?" 
        },
        ...

    }
}