Android
Push Notifications

Push Notifications for Android

A push notification is a message that is immediately delivered to a user device that is either running your client app in the background or idle. Push notifications for Android client apps are sent using Firebase Cloud Messaging (FCM) 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, and then FCM delivers 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, but are delivered only when a user is fully offline on all their devices. For a single-device user, this means that the user must be offline from their device for push notifications to be delivered. For a multi-device user, this means that the user must be offline from all devices for push notifications to be delivered. In other words, if a user is online on one or more devices, notifications aren't delivered and thus not displayed on any devices.

This page provides a step-by-step guide of our push notifications for Android.

Note: Sendbird provides two options for push notifications. Choosing the right push notification option should depend on how much support for multi-device push your client app requires. To learn more, refer to the table at the Push Notifications with Multi-Device Support page.


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 the Send when all devices are offline option.
  3. Register the server key acquired at Step 1-4 by clicking the Add credentials button.
    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 FCM registration tokens. The oldest token will be deleted before a new token is added for a user who already has 20 registration tokens. Only the 20 newest tokens will be maintained for users who already have more than 20.

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 a parameter to 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
    } 
}

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.

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

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.

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

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.

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

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

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.

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

Push notification templates

Push notification templates are pre-formatted forms that can be customized to change the push notification content displayed 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 message templates.

Notification templates

Text messageFile message

Default template

{sender_name}: {message} (ex. John: Hello!)

{filename} (ex. squirrel.jpg)

Alternative template

New message arrived

New file arrived

For the default template, the {sender_name}, {message}, and {filename} fields represent the corresponding string values. Push notifications can be customized by changing these fields.

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

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.
    }
});

Note: The SendBird.PUSH_TEMPLATE_DEFAULT is the default push notification template.

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

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.
        }
    }
});

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": "안녕하십니까?" 
        },
        ...

    }
}