Push Notifications for Android

You can set up Push Notifications so that users can receive messages even when they are offline. Typically, the users can receive push notifications after their app goes into the background. Our latest SDK automatically detects if your app enters the background and updates the user's connection status to Disconnected. Therefore, in normal cases, you do not have to call disconnect() explicitly.

If you do not want to use this auto-detection feature, invoke SendBird.setAutoBackgroundDetection(false).

Note: Push notifications are only supported in Group Channel. The SDK does not provide an option for users to receive push notifications from open channels.

Follow these 4 steps to send push notifications to users of your Android application.

  1. Generate an FCM Server API Key and FCM Sender ID in the Firebase Developer website.
  2. Register an FCM Server API Key and FCM Sender ID in your SendBird Dashboard.
  3. Set up the FCM client code in your Android app.
  4. Register your FCM registration token in the SendBird SDK and parse SendBird FCM messages.

Step 1: Generate FCM Server API Key and FCM Sender ID

If you already have the FCM Server API and FCM Sender ID, skip this step and go to Step 2: Register FCM Server API Key and FCM Sender ID.

  1. Visit the Firebase Console. If do not you have an existing Firebase project for your service, create a new project.

  2. Click the project card to navigate to the Project Overview page.

    Project detail

  3. From the top of left panel, click the gear icon on the right of the project name. From the drop-down menu, select Project Settings.

    Project settings

  4. Select the Cloud Messaging tab under Settings. Under Project Credentials, copy your Server Key and Sender ID.

    Server key and Sender ID

  5. Navigate back to the General tab. If you have not already done so, add Firebase to your Android app by entering your package name and downloading the google-services.json file into your module root directory.

    Add Firebase to app


Step 2: Register FCM Server API Key and FCM Sender ID

Go to your SendBird Dashboard. Navigate to the Settings tab. In the Notifications section, you can see a checkbox enabling push notifications. Select the checkbox, then add your FCM Server Key and Sender ID by clicking Add FCM/GCM and pasting in the values.

Set Push Information

Or, you can also register a FCM Server API Key and FCM Sender ID via the Platform API


Step 3: Set up FCM client code in your Android app

Please follow 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 can also be a helpful reference.

After completing this step, generate a FCM registration token and have skeleton code to handle FCM messages.


Step 4: Register FCM Registration Token in the SendBird SDK and parse SendBird FCM messages

Obtain a FCM Registration token from FirebaseInstanceIdService and pass it to the SendBird SDK. onTokenRefresh() in FirebaseInstanceIdService can be the perfect place to do this.

FirebaseInstanceIdService.class
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String token = FirebaseInstanceId.getInstance().getToken();

    SendBird.registerPushTokenForCurrentUser(token, new SendBird.RegisterPushTokenWithStatusHandler() {
        @Override
        public void onRegistered(SendBird.PushTokenRegistrationStatus ptrs, SendBirdException e) {
            if (e != null) {
                return;
            }

            if (ptrs == SendBird.PushTokenRegistrationStatus.PENDING) {
                // Try registering the token after a connection has been successfully established.
            }
        }
    });
}

Register the token in any Activity instance that calls SendBird.connect().

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

        if (FirebaseInstanceId.getInstance().getToken() == null) return;

        SendBird.registerPushTokenForCurrentUser(FirebaseInstanceId.getInstance().getToken(),
                new SendBird.RegisterPushTokenWithStatusHandler() {
            @Override
            public void onRegistered(SendBird.PushTokenRegistrationStatus status, SendBirdException e) {
                if (e != null) {    // Error.
                    return;
                }
            }
        });
    }
}

You now receives FCM messages from SendBird. Within FirebaseMessagingService, parse the messages to display them to your user.

FirebaseMessagingService.class
@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 message property is the string that is the received text message. The payload property is a JSON string containing full information about the request.

{
    category: "messaging:offline_notification",
    type: string,            // Message Type, User or File or Admin
    message: string,        // User input message
    data: string,            // Custom data field
    custom_type: string,        // Message custom_type
    message_id: long,        // Message ID
    created_at: long,        // 13-digit timestamp
    app_id : string,        // application_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, 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.
}

Notification preferences

Push notifications can be turned on or off for a user.

public 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, invoke 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, invoke this method.
        SendBird.unregisterPushTokenAllForCurrentUser(new SendBird.UnregisterPushTokenHandler() {
            @Override
            public void onUnregistered(SendBirdException e) {
                if (e != null) {    // Error.
                    return;
                }
            }
        });
    }        
}

Or, you can set push notification settings for individual channels.

// If you want to turn push notification for this channel on, set this true.
mGroupChannel.setPushPreference(TRUE_OR_FALSE, new GroupChannelSetPushPreferenceHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

If you want to snooze alarms (notifications) for some periods, invoke SendBird.setDoNotDisturb().

// The current logged-in user doesn't receive push notifications during the specified time.
SendBird.setDoNotDisturb(TRUE_OR_FALSE, START_HOUR, START_MIN, END_HOUR, END_MIN,
        TimeZone.getDefault().getID(),
        new SetDoNotDisturbHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

Push notification message templates

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

Message templates

Text message File message
Default template {sender_name}: {message} (for example, John: Hello!) {filename} (for example, squirrel.jpg)
Alternative template New message arrived New file arrived

{sender_name}, {message}, and {filename} represent the corresponding string values. Use these fields to customize message templates from Dashboard Settings. The option is under Notifications > Push Notification Message Templates.

To choose whether a user receives messages in the form of the default template or the alternative template, call SendBird.setPushTemplate(templateName, handler). templateName is limited to the following two values: SendBird.PUSH_TEMPLATE_DEFAULT, or SendBird.PUSH_TEMPLATE_ALTERNATIVE.

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 default configuration is SendBird.PUSH_TEMPLATE_DEFAULT.

You can check your current setting with SendBird.getPushTemplate().

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