Android
Push Notifications

Push Notifications for Android

Push notifications for Android client apps are sent using Firebase Cloud Messaging (FCM). They are used for keeping your users informed with timely and relevant content, whether your client app is running in the background or a device is idle. They can also perform the types of user interactions such as alert, sound, or badge, and include custom data your app needs to respond to the notifications.

Our Android SDK enables you to build a client app which can receive push notifications. When a message is sent to SendBird server through the SDK, the server communicates with FCM regarding the message and then FCM delivers a push notification for the message to an Android device where your client app is installed.

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

This page mainly describes how to obtain server key and sender ID for FCM from the Firebase console and how to setup your Android client app with the SDK to receive push notifications.

Note: Push notifications are supported in group channels only, and are not available in open channels.


Step 1: Generate server key and sender ID for FCM

In order to send notification requests to FCM on behalf of your server, SendBird server needs your own server key and sender ID which FCM requires to authorize HTTP requests. The server uses two credentials just to communicate with FCM. (If you already have the server key and sender ID, skip this step and go to Step 2: Register server key and sender ID to SendBird Dashboard.)

  1. Visit the Firebase console. If you don't have a Firebase project for your service, create a new project.
    Project detail
  2. Click the project card to move to the Project Overview.
  3. At the upper left corner, click the gear icon beside the project name. From the context menu, select the Project Settings.
    Project settings
  4. Under Settings > Cloud Messaging > Project credentials, copy your server key and sender ID.
    Server key and Sender ID
  5. Move to the General tab and select an Android platform to add Firebase to your Android app. In the prompted registration process, enter a package name, download the google-services.json file, move it into your Android app module root directory. Add firebase to Android App

Step 2: Register server key and sender ID to SendBird Dashboard

You can register your server key and sender ID to SendBird server through the dashboard, or by using the platform API's add a GCM push configuration action. The following shows the dashboard case.

  1. Sign in to your dashboard and go to the Settings menu.
  2. In the Notifications tab, you can see a checkbox turning on push notifications. Select the checkbox, then register the copied server key and sender ID at the Step 1-4 above by clicking the Add FCM/GCM button.
    Set Push Information

Step 3: Set up your Android FCM client app

Refer to Firebase's Set Up a Firebase Cloud Messaging client app on Android guide on adding configuration code to your Android project to handle FCM messages. The Google FCM sample project is another helpful reference as well.

Note: On initial startup of your app, the FCM SDK generates a registration token for the client app instance on your user's device. This registration token is a globally-unique and app-specific identifier of a client app instance, which FCM uses to determine which device to send push notifications to. Make sure that you check the Step 4 below on a registration token when referring to the guides above.


Step 4: Register a device registration token to SendBird server

When FCM is requested to send push notifications to a specific client app on an Android device, FCM requires the app instance's registration token which has been issued by itself. Therefore, to send notification requests to FCM on behalf of your server, SendBird server needs every registration tokens of your client app instances.

If the FCM SDK generates a registration token successfully on initial startup of your app, this token is passed to the onNewToken() callback. Like the following code, you should register a registration token to SendBird server by passing it as a parameter to the registerPushTokenForCurrentUser() method.

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, we recommend that you 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 afterward.

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 a FCM message payload

Refer to Firebase's Receive messages in an Android app guide on how to implement code to receive and parse FCM notification messages. The guide provides you with how notification messages are handled depending on the state of the receiving app (foreground/background), how to edit the app manifest, and how to override the onMessageReceived method.

The following code shows how to parse a notification message payload which consists of two properties, message and sendbird. The message property is a string that is generated based on a chosen message template. The sendbird property is a JSON object which contains full information on the request. Within the MyFirebaseMessagingService.java, you can display the parsed messages to users with your custom sendNotification() method.

MyFirebaseMessagingService.java
Light Color Skin
Copy
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    String message = remoteMessage.getData().get("message");
    JsonElement payload = new JsonParser().parse(remoteMessage.getData().get("sendbird"));
    sendNotification(message, payload);
}

private void sendNotification(String message, JsonElement payload) {  
    // Your own way to show notifications to users.
}

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

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,             // Customized alert push message 
    push_sound: string,             // The location of a sound file for push notifications
    audience_type: string,          // The type of audiences to receive push 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

The following shows how to register and unregister the current user's registration token to SendBird server to enable and disable push notifications in the user's client app.

Note: The registration/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 the all devices of the user, call this method.
        SendBird.unregisterPushTokenAllForCurrentUser(new SendBird.UnregisterPushTokenHandler() {
            @Override
            public void onUnregistered(SendBirdException e) {
                if (e != null) {    // Error.
                    return;
                }
            }
        });
    }        
}

If needed, at the current user's client app, you can determine the type of push notification trigger to customize when to deliver notifications. For customization, the SendBird.PushTriggerOption provides the following three options:

  • ALL: the user receives push notifications for all new messages while offline, including mentioned messages.
  • OFF: no push notifications are delivered to the user.
  • MENTION_ONLY: the user receives push notifications only for the mentioned messages while offline.
Light Color Skin
Copy
// If you want to trigger push notifications 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;
        }
    }
} 

At the channel level, you can also determine the type of push notification trigger by individual channel, and turn on or off notifications for the channel. For this, the GroupChannel.PushTriggerOption provides the following four options:

  • ALL: the user receives push notifications for all new messages in the channel while offline, including mentioned messages.
  • OFF: no push notifications are delivered to the channel.
  • MENTION_ONLY: the user receives push notifications only for the mentioned messages in the channel while offline.
  • DEFAULT: the user's push notification trigger setting automatically applies to the channel.
Light Color Skin
Copy
// If you want to automatically apply the user's push notification setting 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 push notifications 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 suppress push notifications on the current user's client app during specific time of every day, use our Do Not Disturb feature like the following.

Note: You can also set a user's Do Not Disturb with the platform API's update push preferences action.

Light Color Skin
Copy
// The current user will not receive push notifications 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;
        }
    }
});

If you want to snooze push notifications for a specific period of time, use our snooze feature like the following.

Note: You can also snooze the notifications for a user with the platform API's update push preferences action.

Light Color Skin
Copy
// The current user will not receive push notifications 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 message templates

Push notification message templates are forms about how the content of a notification message is displayed when the message arrives to a user's device. You can choose between the default template and alternative template, both of which are customizable.

Message templates

Text messageFile message

Default template

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

{filename} (ex. squirrel.jpg)

Alternative template

New message arrived

New file arrived

The {sender_name}, {message}, and {filename} above represent the corresponding string values. Use these fields to customize message templates from your dashboard's Settings > Application > Notifications tab. The option is under the Push Notification Message Templates part.

To determine what type of template applies to push notifications, use the setPushTemplate() method. You can specify the name of a template with 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: By default, a message template is SendBird.PUSH_TEMPLATE_DEFAULT.

You can check your current setting with getPushTemplate() like the following.

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