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 with multi-device support

Copy link

Sendbird’s push notifications with multi-device support provide the same features as our general push notifications, but with additional support for multi-device users. If implemented, notifications are delivered to all online and offline devices of a multi-device user. However, through our Chat SDK for Android, push notifications are displayed only on offline devices, while ignored by online devices. As a result, client apps are able to display push notifications on all offline devices, regardless of whether one or more are online.

For example, let’s say a multi-device user who has six devices installed with your client app is online on one device and offline on the remaining five. If push notifications are implemented, notifications aren’t delivered to any devices. If push notifications with multi-device support are implemented, notifications are delivered to all six devices, but displayed only on the five devices that are offline.

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 call the disconnect() method.

Understanding the differences

Copy link

To find out which push notifications best suits your client app use cases, refer to the table below:

General push notificationsPush notifications with multi-device support

Send when

All devices are offline.

As long as one device is offline.

Notification messages

Single-device user: Displayed when disconnected from the server and thus offline.

Multi-device user: Displayed only when all devices are offline.

Single-device user: Displayed when disconnected from the server and thus offline.

Multi-device user: Displayed on all offline devices, regardless of whether one or more are online.

SDK's event callback

Invoked only when the app is connected to Sendbird server.

Invoked only when the app is connected to Sendbird server.

App instance's registration token

Can be manually registered to Sendbird server.

Automatically registered to Sendbird server.

Notification preferences

Can be set by application and group channel.

N/A

Push notification templates

Supported.

Supported.

Push notification translation

Supported by Google Cloud Translation API.

Supported by Google Cloud Translation API.


Push notifications for FCM

Copy link

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

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 your client app, create a new project.
  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.
  4. Go to Cloud Messaging > Project credentials and copy your 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.

Step 2: Register server key to Sendbird Dashboard

Copy link

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

  1. Sign in to your dashboard and go to Settings > Application > Notifications.
  2. Turn on Notifications and select the Send as long as one device is 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 the platform API's add an FCM push configuration action.

Step 3: Set up Firebase and the FCM SDK

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'
}

Then the Chat SDK writes and declares our push notifications with multi-device support in the manifest while you build your client app. If you declare another push service that extends FirebaseMessagingService in your client app's manifest, this multi-device support will not work in the app.

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: Implement multi-device support in your Android app

Copy link

The following classes and interface are provided to implement push notifications with multi-device support:

Class or interfaceDescription

SendBirdPushHandler

A class that provides the onNewToken(), onMessageReceived(), and other callbacks to handle a user's registration token and receive notification messages from FCM.

SendBirdPushHelper

A class that provides the methods to register and unregister a SendBirdPushHandler handler, check if the same message has already been received, and more.

OnPushTokenReceiveListener

An interface that contains the onReceived() callback to receive a user's registration token from FCM.

These are used to inherit your MyFirebaseMessagingService class from the SendBirdPushHandler class and implement the following:

public class MyFirebaseMessagingService extends SendBirdPushHandler {

    private static final String TAG = "MyFirebaseMsgService";
    private static final AtomicReference<String> pushToken = new AtomicReference<>();

    public interface ITokenResult {
        void onPushTokenReceived(String pushToken, SendBirdException e);
    }

    @Override
    public void onNewToken(String token) {
        pushToken.set(token);
    }

    // Invoked when a notification message has been delivered to the current user's client app.
    @Override
    public void onMessageReceived(Context context, 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("push_title"), remoteMessage.getData().get("message"), channelUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected boolean isUniquePushToken() {
        return false;
    }

    // alwaysReceiveMessage() determines whether push notifications for new messages
    // will be delivered even when the app is in foreground.
    // The default is false, meaning push notifications will be delivered
    // only when the app is in the background.
    @Override
    protected boolean alwaysReceiveMessage() {
        return false;
    }

    public static void sendNotification(Context context, String messageTitle, String messageBody, String channelUrl) {
        // Customize your notification containing the received FCM message.
    }

    public static void getPushToken(ITokenResult listener) {
        String token = pushToken.get();
        if (!TextUtils.isEmpty(token)) {
            listener.onPushTokenReceived(token, null);
            return;
        }

        SendBirdPushHelper.getPushToken((newToken, e) -> {
            if (listener != null) {
                listener.onPushTokenReceived(newToken, e);
            }

            if (e == null) {
                pushToken.set(newToken);
            }
        });
    }
}

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.

In order to receive information about push notification events for the current user from Sendbird server, register a MyFireBaseMessagingService instance to the SendBirdPushHelper as an event handler. It is recommended to register the instance in the onCreate() method of the Application instance as follows:

public class MyApplication extends Application {
    private static final String APP_ID = "YOUR_APP_ID";
    ...

    @Override
    public void onCreate() {
        super.onCreate();
        SendBird.init(APP_ID, getApplicationContext());
        SendBirdPushHelper.registerPushHandler(new MyFirebaseMessagingService());
    }
}

Also, register a MyFireBaseMessagingService instance when a user logs into Sendbird server as follows:

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

        SendBirdPushHelper.registerPushHandler(new MyFirebaseMessagingService());
    }
});

The instance should be unregistered when a users logs out from Sendbird server as follows:

SendBirdPushHelper.unregisterPushHandler(IS_UNREGISTER_ALL, new SendBirdPushHelper.OnPushRequestCompleteListener() {
    @Override
    public void onComplete(boolean isRegistered, String token) {
        SendBird.disconnect(new SendBird.DisconnectHandler() {
            @Override
            public void onDisconnected() {
                // Clear user-related data.
            }
        });
    }

    @Override
    public void onError(SendBirdException e) {
        // 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_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
}

Step 6: Enable multi-device support in the Dashboard

Copy link

After the above implementation is completed, multi-device support should be enabled in your dashboard by going to Settings > Application > Notifications > Push notifications for multi-device users.


Push notifications for HMS

Copy link

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

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 your 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 > Application > 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.

Step 3: Set up Huawei Message Service and the HMS SDK

Copy link

Add the following dependency for the Cloud Messaging 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:1.1.1.300'
    }
}

Then the Chat SDK writes and declares our push notifications with multi-device support in the manifest while you build your client app. If you declare another push service that extends FirebaseMessagingService in your client app's manifest, this multi-device support will not work in the app.

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: Implement multi-device support in your Android app

Copy link

The following classes and interface are provided to implement push notifications with multi-device support:

Class or interfaceDescription

SendBirdHmsPushHandler

A class that provides the onNewToken(), onMessageReceived(), and other callbacks to handle a user's registration token and receive notification messages from HMS.

SendBirdPushHelper

A class that provides the methods to register and unregister a SendBirdHmsPushHandler handler, check if the same message has already been received, and more.

OnPushTokenReceiveListener

An interface that contains the onReceived() callback to receive a user's registration token from HMS.

These are used to inherit your MyHmsMessagingService class from the SendBirdHmsPushHandler class and implement the following:

public class MyHmsMessagingService extends SendBirdHmsPushHandler {

    private static final String TAG = "MyHmsMessagingService";
    private static final AtomicReference<String> pushToken = new AtomicReference<>();

    public interface ITokenResult {
        void onPushTokenReceived(String pushToken, SendBirdException e);
    }

    @Override
    public void onNewToken(String token) {
        Log.i(TAG, "onNewToken(" + token + ")");
        pushToken.set(token);
    }

    @Override
    public void onMessageReceived(Context context, 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");

                // Also if you intend on generating your own notifications as a result of a received HMS
                // message, here is where that should be initiated. See the sendNotification method below.
                sendNotification(context, remoteMessage.getDataOfMap().get("message"), channelUrl);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean isUniquePushToken() {
        return false;
    }

    @Override
    protected Context getContext() {
        Log.e("==", "getContext()");
        // Application context is returned.
        Return APPLICATION_CONTEXT;
    }

    public static void sendNotification(Context context, String messageBody, String channelUrl) {
        // Customize your notification containing the received HMS message.
    }

    public static void getPushToken(ITokenResult listener) {
        String token = pushToken.get();
        if (!TextUtils.isEmpty(token)) {
            listener.onPushTokenReceived(token, null);
            return;
        }

        SendBirdPushHelper.getPushToken((newToken, e) -> {
            if (listener != null) {
                listener.onPushTokenReceived(newToken, e);
            }

            if (e == null) {
                pushToken.set(newToken);
            }
        });
    }
}

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.

In order to receive information about push notification events for the current user from Sendbird server, register a MyHmsMessagingService instance to the SendBirdPushHelper as an event handler. It is recommended to register the instance in the onCreate() method of the Application instance as follows:

public class MyApplication extends Application {
    private static final String APP_ID = "YOUR_APP_ID";
    ...

    @Override
    public void onCreate() {
        super.onCreate();
        SendBird.init(APP_ID, getApplicationContext());
        SendBirdPushHelper.registerHmsPushHandler(new MyHmsMessagingService());
    }
}

Also, register a MyHmsMessagingService instance when a user logs into Sendbird server as follows:

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

        SendBirdPushHelper.registerHmsPushHandler(new MyHmsMessagingService());
    }
});

The instance should be unregistered when a users logs out from Sendbird server as follows:

SendBirdPushHelper.unregisterPushHandler(IS_UNREGISTER_ALL, new SendBirdPushHelper.OnPushRequestCompleteListener() {
    @Override
    public void onComplete(boolean isRegistered, String token) {
        SendBird.disconnect(new SendBird.DisconnectHandler() {
            @Override
            public void onDisconnected() {
                // Clear user-related data.
            }
        });
    }

    @Override
    public void onError(SendBirdException e) {
        // Handle error.
    }
});

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");

            // If you want 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
}

Step 6: Enable multi-device support in the Dashboard

Copy link

After the above implementation is completed, multi-device support should be enabled in your dashboard by going to Settings > Application > Notifications > Push notifications for multi-device users.