Quick Start

SendBird helps you to add real-time chat to any app with speed and efficiency. The Android SDK specifically provides you with methods to initialize and configure chat from the client side - no backend required. This quick start section presents a succinct overview of the SDK’s functionalities and logic, then guide you through the preliminary steps of setting up SendBird in your own app.


First, try out the sample app!

Our open-source sample app is a fully functional messaging app built upon material design principles. Download and build the sample from GitHub to chat freely with other people. The app gives you a sense of what you can build using SendBird, although it is by no means the limit of its capabilities.

The sample app is a useful reference when developing your own project using SendBird. In fact, a convenient way to implement chat is to build your app on top of the sample. Note that you must change the App ID to your own in this case - reference the Create a new SendBird Application from the Dashboard section.


How messaging with SendBird works

Messaging with the SendBird SDK is simple: a user connects, enters a channel, send a message to the channel, and receives the messages from all other users within the channel. There are two types of channels: Open and Group Channel. Open Channel is a public channel; anyone can enter and chat freely. Group Channel is a private channel that can be joined through invitation only. 1-to-1 messaging is simply a group channel with two members.

When using the SDK, messages are automatically received with Channel Handlers. As long as a user is connected, incoming messages and other relevant events trigger callback methods such as onMessageReceived(channel, message), onUserJoined(channel, user), etc., delivering message or channel objects containing the latest information.


Install and configure dependencies

Step 1: Create a new SendBird application from the Dashboard

A SendBird application houses everything that goes in a chat service - users, messages, and channels. Create a new SendBird application by singing in to the SendBird Dashboard. If you do not yet have an account, you can sign up with Google, GitHub, or create a new account.

Once you create an application, all users within can communicate with each other, across all platforms. This means users using iOS, Android, and web clients can all chat with one another without any additional setup. However, all data is limited to the scope of one application, meaning users in different SendBird applications cannot talk to each other.

Step 2: Install the SDK

Installing the SDK is a straightforward process if you’re familiar with using external libraries or SDK’s in your projects. To install the SendBird SDK using Gradle, add the following lines to your app-level build.gradle file.

build.gradle
repositories {
    maven { url "https://raw.githubusercontent.com/smilefam/SendBird-SDK-Android/master/" }
}
dependencies {
    compile 'com.sendbird.sdk:sendbird-android-sdk:3.0.60'
}

Alternatively, you can download the .jar file from the link below. Copy this file into your libs/ folder, and make sure you include the library in your build.gradlefile as well.

Step 3: Grant system permissions

The SendBird SDK requires system permissions. These permissions allow the SDK to communicate with the SendBird servers and read/write files to a device's external storage.

Add the following lines to your AndroidManifest.xml file.

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

<!-- READ/WRITE_EXTERNAL_STORAGE permissions are required to upload or download files from/into external storage. ->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Step 4: Configure ProGuard (optional)

When you build your app apk with minifyEnabled true, add the following line to the module's proguard-rules property file.

-dontwarn com.sendbird.android.shadow.**

Sending your first message

The SendBird SDK abstracts messaging into a simple and straightforward process. To send your first message, do the following steps:

Note: The following methods, excluding SendBird.init(), are asynchronous. This means that you must ensure that you've received a successful callback before proceeding to the next step. A simple way to do this is the nest methods - see the example in Step 4: Enter the channel when channel.enter() is called after receiving an OpenChannel.getChannel() callback.

Step 1: Initialize the SDK

Initialization binds the SDK to Android’s context, thereby allowing it to respond to connection and state changes. Pass in the App ID of the SendBird application you created earlier in the Dashboard to initialize the SDK.

Note: SendBird.init() must be called once across the entire application. onCreate() of Application class is the best place to initialize.

SendBird.init(APP_ID, Context context);

Step 2: Connect

Connect a user to SendBird’s servers using their User ID. Any untaken user ID creates a new user in the SendBird application before connecting, while an existing ID makes the user log in directly. Authentication with Access Tokens are discussed in the Authentication section.

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

Step 3: Create a channel

Create an open channel. Once created, all users in the SendBird application can freely enter the channel to converse.

Note: A group channel can be created in a similar manner. However, to have other users join the channel, an existing member of the channel (for example, the creator) must invite them first.

OpenChannel.createChannel(new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Step 4: Enter the channel

Enter the channel to view and send messages.

OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }

        openChannel.enter(new OpenChannel.OpenChannelEnterHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {
                    // Error.
                    return;
                }
            }
        });
    }
});

Step 5: Send a message

And finally, send a message! There are three types of messages: a User Message is a plain text message, a File Message is a binary file, such as an image or PDF, and an Admin Message is a special type of message sent through the Dashboard or Platform API.

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Authentication

To use SendBird's features, first do the following authentication tasks.


Initializing with APP_ID

To use the chat features, you must initialize SendBird using the APP_ID assigned to your SendBird application. Typically, initialization is implemented in the user login Activity.

SendBird.init(APP_ID, context);

Connecting with UserID

By default, SendBird requires only a UserID to join a channel. Upon requesting connection, SendBird queries its user database for a matching UserID. If it finds that the UserID has not been registered yet, SendBird creates a new user account. The UserID can be any unique string id, such as an email address or a UID from your database.

This simple authentication procedure is useful when you are in development or if your service does not require additional security.

Note: Explanation on SendBird's usage of Handlers and callbacks can be found under the Event Handler section.

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

Note: You must connect to SendBird before calling any methods through the SDK (apart from init()). If you attempt to call a method without connecting, you may receive an API-TOKEN is missing error.


Connecting with UserID and Access Token

With the SendBird Platform API, you can create a user with an access token, or you can issue an access token for an existing user. Once an access token is issued, you are required to provide the user's token in the login method.

  1. Create a SendBird user account via the Platform API when your user signs up on your service.
  2. Save the access token to your secured persistent store.
  3. Load the access token in your client and pass it to the SendBird login method.
  4. For security reasons, we recommend that you periodically update your access token by issuing a new token to replace the previous one.

Note: You can set restrictions for users without access tokens in your Dashboard settings. These settings can be found under Security - Access Token Policy.

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

Disconnecting

Disconnect from SendBird when your user no longer needs to receive messages from an online state. But users receive Group Channel messages through Push Notifications.

Disconnecting removes all registered handlers and callbacks. That is, it removes all Event Handlers added through SendBird.addChannelHandler() or SendBird.addConnectionHandler(). It also flushes all internally cached data, such as the channels that are cached when OpenChannel.getChannel() or GroupChannel.getChannel() is called.

SendBird.disconnect(new SendBird.DisconnectHandler() {
    @Override
    public void onDisconnected() {
        // You are disconnected from SendBird.
    }
});

Updating a user profile and profile image

You can update a user's nickname and profile image. Call updateCurrentUserInfo() to update a user's nickname, as well as their profile picture with a URL.

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

        SendBird.updateCurrentUserInfo(NICKNAME, PROFILE_URL, new UserInfoUpdateHandler() {
            @Override
            public void onUpdated(SendBirdException e) {
                if (e != null) {
                    // Error.
                    return;
                }
            }
        });
    }
});

Or, you can upload an image directly using updateCurrentUserInfoWithProfileImage().

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

        SendBird.updateCurrentUserInfoWithProfileImage(NICKNAME, FILE, new UserInfoUpdateHandler() {
            @Override
            public void onUpdated(SendBirdException e) {
                if (e != null) {
                    // Error.
                    return;
                }
            }
        });
    }
});

Channel Types

We recommend you to understand the following terminology before proceeding with the rest of this guide.


Open Channel

Open Channel is a public chat. In this channel type, anyone can enter and participate in the chat without permission. A single channel can handle thousands of simultaneous users like Twitch-style public chat.


Group Channel

A Group Channel is a private chat. A user may join the chat only through an invitation by another user who is already a member of the chatroom.

  • Distinct property : A channel with the Distinct property turned on is always reused for the same members. If a new member is invited, or if a member leaves the channel, then the Distinct property is disabled automatically.

  • 1-on-1 messaging: 1-on-1 messaging is a private channel between two users. You can turn on the Distinct property for the channel to reuse a channel for the same members like Twitter Direct Messages-style 1-on-1 chatting.

  • Group messaging: Group messaging is a private channel among multiple users. You can invite up to hundreds of members into a group channel like WhatsApp-style closed group chat.


Open Channel vs. Group Channel

Type Open Channel Group Channel
Access control Public Invitation required
Class name OpenChannel GroupChannel
Number of members Over a few thousand Less than a few hundred
How to create SendBird Dashboard / Platform API / Client SDK Client SDK / Platform API
Operators Supported N/A
User ban Supported N/A
User mute Supported N/A
Freeze channel Supported N/A
Push notifications N/A Supported
Unread counts N/A Supported
Read receipts N/A Supported
Typing indicators N/A Supported

Open Channel

Open Channel is a public chat. In this channel type, anyone can enter and participate in the chat without permission. A single channel can handle thousands of simultaneous users like Twitch-style public chat.


Creating an open channel

Open Channel is ideal for use cases that require a small and static number of channel. To create an open channel from the SendBird Dashboard, do the following:

In the dashboard, click OPEN CHANNELS, then click CREATE at the top-left corner. In the dialog box that appears, specify the name, url, cover image, and custom type of a channel. The channel url is a unique identifier.

You can also create a channel on demand or dynamically via the SDK or the SendBird Platform API.

OpenChannel.createChannel(new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can also append information by passing additional arguments.

OpenChannel.createChannel(NAME, COVER_IMAGE_OR_URL, DATA, CUSTOM_TYPE, HANDLER)
  • NAME: the name of a channel, or the channel topic.
  • COVER_IMAGE_OR_URL: the file or URL of the cover image, which you can fetch to render into the UI.
  • DATA: the String field to store structured information, such as a JSON String.
  • CUSTOM_TYPE: the String field that allows you to subclassify your channel.

Note: See the Advanced section for more information on cover images and custom types.


Getting a list of open channels

You can obtain a list of all open channels by creating a OpenChannelListQuery. The next() method returns a list of OpenChannel objects.

OpenChannelListQuery channelListQuery = OpenChannel.createOpenChannelListQuery();
channelListQuery.next(new OpenChannelListQuery.OpenChannelListQueryResultHandler() {
    @Override
    public void onResult(List<OpenChannel> channels, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Getting an open channel instance with a URL

Since a channel URL is a unique identifier of an open channel, you can use a URL to retrieve a channel instance. It is important to remember that a user must enter the channel to send or receive messages within it.

Store channel URLs to handle lifecycle or state changes in your app. For example, if a user disconnects from SendBird by temporarily switching to another app, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance, then re-entering the user into the channel.

OpenChannel.getChannel(channelUrl, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }

        // Successfully fetched the channel.
        // Do something with openChannel.
    }
});

Entering an open channel

A user must enter an open channel to receive messages. You can enter up to 10 open channels at once.

Entered open channels are valid only within the current connection. If you disconnect or reconnect to SendBird, you must re-enter channels to continue receiving messages.

OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }

        openChannel.enter(new OpenChannel.OpenChannelEnterHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {
                    // Error.
                    return;
                }
            }
        });
    }
});

Exiting the open channel

To stop receiving messages from the open channel, you must exit the channel.

OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }

        openChannel.exit(new OpenChannel.OpenChannelExitHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {
                    // Error.
                    return;
                }
            }
        });
    }
});

Sending messages

In an entered channel, a user can send messages of the following types:

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.

You can additionally specify a CUSTOM_TYPE to further subclassify a message. When you send a text message, you can additionally attach arbitrary strings via a data field. You can utilize this field to send structured data such as font sizes, font types, or custom JSON objects.

Delivery failures due to the network issues return an exception. By overriding the onSent()callback within an implementation of sendUserMessage(), it is possible to display only the messages that are successfully sent.

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

A user can also send any binary file through SendBird. There are two ways in which you can send a binary file: by sending the file itself, or by sending a URL.

Sending a raw file means that you upload it to the SendBird servers. Alternatively, you can choose to send a file hosted in your own servers by passing in a URL that points to the file. In this case, your file isn't hosted in the SendBird servers, and downloaded through your own servers instead.

Note: If you upload your file directly, a size limit is imposed per file. This limit depends on your plan, and can be viewed from your Dashboard. No file size limit is imposed if you send a file message via a URL. Then the file isn't uploaded to the SendBird servers.

// Sending file message with raw file
channel.sendFileMessage(FILE, NAME, TYPE, SIZE, DATA, CUSTOM_TYPE, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

// Sending file message with file URL
channel.sendFileMessage(FILE_URL, NAME, TYPE, SIZE, DATA, CUSTOM_TYPE, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Note: To send metadata along with a file, you can populate the DATA field.


Receiving messages

Messages can be received by adding a ChannelHandler. A received BaseMessage object is one of the following three message types.

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.
  • AdminMessage: message sent by an admin through the Platform API.

UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        if (baseMessage instanceof UserMessage) {
            // message is a UserMessage
        } else if (baseMessage instanceof FileMessage) {
            // message is a FileMessage
        } else if (baseMessage instanceof AdminMessage) {
            // message is an AdminMessage
        }
    }
});

Loading previous messages

You can load previous messages by creating a PreviousMessageListQuery instance and calling load(). You can display the past messages in your UI once they have loaded.

PreviousMessageListQuery prevMessageListQuery = openChannel.createPreviousMessageListQuery();
prevMessageListQuery.load(30, true, new PreviousMessageListQuery.MessageListQueryResult() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Past messages are queried in fixed numbers (30 in the above code). A new PreviousMessageListQuery instance loads the most recent n messages. load() on the same query instance returns n messages before that. So if you store your query instance as a member variable, you can traverse through your entire message history.

Note: You must receive your first onResult() callback before invoking load() again.


Loading messages by timestamp

You can retrieve a set number of messages starting from a specific timestamp. To load messages sent prior to a specifed timestamp, use channel.getPreviousMessagesByTimestamp().

channel.getPreviousMessagesByTimestamp(timestamp, isInclusive,
        prevResultSize, reverse, messageType, customType,
        new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> list, SendBirdException e) {
        if (e != null) {
            return;
        }

        // Successfully fetched list of messages sent before timestamp.
    }
});
  • timestamp: the reference timestamp.
  • isInclusive: whether to include messages sent exactly at timestamp.
  • prevResultSize: the number of messages to load. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the earliest message.
  • reverse: whether to reverse the results.
  • messageType: a BaseChannel.MessageTypeFilter object. Possible values are limited to MessageTypeFilter.USER, MessageTypeFilter.FILE, MessageTypeFilter.ADMIN, or MessageTypeFilter.ALL.
  • customType: the custom type of the messages to be returned.

To load messages sent after a specified timestamp, call channel.getNextMessagesByTimestamp() in a similar fashion. To load results on either side of the reference timestamp, use channel.getPreviousAndNextMessagesByTimestamp().


Getting a list of participants in a channel

Participants are online users who are currently receiving all messages from the open channel.

UserListQuery userListQuery = openChannel.createParticipantListQuery();
userListQuery.next(new UserListQuery.UserListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Getting participants' online statuses

To stay updated on each participant's connection status, you must obtain a new UserListQuery, which contains the latest information on each user. To get a UserListQuery for a specific channel, call channel.createParticipantListQuery(). If you want to get the list of all users of your app, call SendBird.createUserListQuery().

You can check each of the users' connection statuses by calling user.getConnectionStatus(). getConnectionStatus() returns one of three values:

  • User.ConnectionStatus.NON_AVAILABLE: user's status information cannot be reached.
  • User.ConnectionStatus.OFFLINE: user is disconnected from SendBird.
  • User.ConnectionStatus.ONLINE: user is connected to SendBird.

Note: If your app needs to keep track of users' connection statuses in real time, we recommend you to receive a new UserListQuery periodically, perhaps in intervals of one minute or more.


Getting a list of banned or muted users in a channel

You can also create a query to get a list of muted or banned users in an open channel. This query is only available for users who are registered as operators of the open channel.

UserListQuery bannedUserListQuery = openChannel.createBannedUserListQuery(); //or createMutedUserListQuery()
bannedUserListQuery.next(new UserListQuery.UserListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Deleting messages

Users can delete messages. An error is returned if a user tries to delete messages sent by someone else. Also channel operators can delete any message in the channel, including those by other users.

Deleting a message fires a MessageDeleted event to all other users in the channel.

channel.deleteMessage(BASE_MESSAGE, new BaseChannel.DeleteMessageHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can receive a MessageDeleted event using a ChannelHandler.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageDeleted(BaseChannel baseChannel, long messageId) {
    }
});

Open Channel: Advanced

This section explains the premium features of Open Channel. Some are available only to a paying user.


Admin messages

You can send an admin message to users in a channel using the SendBird Dashboard or the Platform API. To send the admin message via the Dashboard, in the Open Channels panel, select an open channel, find a message box below, click the Admin Message tab, and write a message in the box. The admin message is limited to 1000 characters.

Note: If you are currently developing under the Free Plan and therefore cannot use the Moderation Tools from the Dashboard, you must send the admin messages through the Platform API.


Channel cover images

When creating a channel, you can add a cover image by specifying an image URL or file.

OpenChannel.createChannel(NAME, COVER_URL, DATA, new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can get the cover image URL using getCoverUrl(), and update a channel's cover image by calling updateChannel().


Custom channel types

When creating a channel, you can additionally specify a custom type to further subclassify your channels. This custom type takes on the form of a String, and can be handy in searching or filtering channels.

Note: DATA and CUSTOM_TYPE are both String fields that allow you to append information to your channels. The intended use case is for CUSTOM_TYPE to contain information that can subclassify the channel (for example, distinguishing "School" and "Work" channels). However, both these fields can be flexibly utilized.

channel.createChannel(NAME, COVER_URL, DATA, CUSTOM_TYPE new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

To get a channel's custom type, call channel.getCustomType().


Custom message types

Likewise, you can specify a custom type for messages to categorize them into more specific groups. This custom type takes on the form of a String, and can be useful in searching or filtering messages.

Note: DATA and CUSTOM_TYPE are both String fields that allow you to append information to your messages. The intended use case is for CUSTOM_TYPE to contain information that can subclassify the message (for example, distinguishing "FILE_IMAGE" and "FILE_AUDIO" type messages). However, both these fields can be flexibly utilized.

To embed a custom type into a message, pass a String parameter to channel.sendUserMessage() or channel.sendFileMessage().

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

To get a message's custom type, call message.getCustomType().


Message auto-translation

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

SendBird makes it possible for messages to be sent in different languages through its auto-translation feature. Pass in a List of language codes to sendUserMessage() to request translated messages in the corresponding languages.

ArrayList targetLangList = new ArrayList<String>();
targetLangList.add("es");
targetLangList.add("ko");

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, targetLangList, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can obtain translations of a message using userMessage.getTranslations(). This method returns a Map containing the language codes and translations.

SendBird.addChannelHandler(UNIQUE_CHANNEL_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        Map<String, String> map = ((UserMessage) baseMessage).getTranslations();
        String esTranslation = map.get("es");
        ...
        // Display translation in UI.
    }
}

Note: The message auto-translation supports 53 languages. For the language code table, see the Miscellaneous > Supported Languages.


You can search for specific channels by adding a keyword to your OpenChannelListQuery. There are two types of keywords: a Name Keyword and a URL Keyword.

A query containing the Name Keyword returns the list of open channels that have the keyword included in their names.

channelListQuery = OpenChannel.createOpenChannelListQuery();
channelListQuery.setNameKeyword("NameKeyword");

channelListQuery.next(new OpenChannelListQuery.OpenChannelListQueryResultHandler() {
    @Override
    public void onResult(List<OpenChannel> channels, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }
        // Returns a List of channels that have "NameKeyword" in their names.
    }
});

A query containing the URL Keyword returns the open channel whose URL matches the given keyword exactly.

channelListQuery = OpenChannel.createOpenChannelListQuery();
channelListQuery.setUrlKeyword("UrlKeyword");

channelListQuery.next(new OpenChannelListQuery.OpenChannelListQueryResultHandler() {
    @Override
    public void onResult(List<OpenChannel> channels, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }
        // Returns a List containing a single channel with the URL that matches the URL Keyword.
    }
});

File message thumbnails

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

When sending an image file, you can choose to create thumbnails of the image, which you can fetch and render into your UI. You can specify up to 3 different dimensions to generate thumbnail images in, which can be convenient for supporting various display densities.

Note: Supported file types are files whose media type is image/* or video/*. The SDK does not support creating thumbnails when sending a file message via a file URL.

Create a List of FileMessage.ThumbnailSize objects to pass to channel.sendFileMessage(). A ThumbnailSize can be created with the constructor ThumbnailSize(int maxWidth, int maxHeight), where the values specify pixels. The onSent() callback subsequently returns a List of Thumbnail objects that each contain the URL of the generated thumbnail image file.

List<FileMessage.ThumbnailSize> thumbnailSizes = new ArrayList<>();
// Create and add ThumbnailSizes (Max: 3 ThumbnailSizes).
thumbnailSizes.add(new ThumbnailSize(100, 100));
thumbnailSizes.add(new ThumbnailSize(200, 200)); 

channel.sendFileMessage(file, name, type, size, data, customtype, thumbnailSizes, new BaseChannel.SendFileMessageHandler() {
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error!
        }

        Thumbnail first = fileMessage.getThumbnails.get(0);
        Thumbnail second = fileMessage.getThumbnails.get(1);

        int maxHeightFirst = first.getMaxHeight(); // 100
        int maxHeightSecond = second.getMaxHeight(); // 200

        String urlFirst = first.getUrl(); // URL of first thumbnail file.
        String urlSecond = second.getUrl(); // URL of second thumbnail file.
    }
}

maxWidth and maxHeight specify the maximum dimensions of the thumbnail. Your image is resized evenly to fit within the bounds of (maxWidth, maxHeight). Note that if the original image is smaller than the specified dimensions, the thumbnail isn't resized. getUrl() returns the location of the generated thumbnail file within the SendBird servers.

Group Channel

Group Channel is a private chat. A user may join the chat only through an invitation by another user who is already a member of the chatroom. A group channel can consist of one to hundreds of members. Creating a channel with two members allows 1-to-1 messaging.

A user automatically receives all messages from the group channels that they are a member of.


Creating a group channel

A group channel can be created on demand by a user through the SendBird SDK.

Distinct property : A channel with the Distinct property turned on is always reused for the same members. If a new member is invited, or if a member leaves the channel, then the distinct property is disabled automatically. For example, in the case that a group channel with 3 members, A, B, and C, already exists, attempting to create a new channel with the same members just returns a reference to the existing channel.

Consequently, we recommend that you turn on the Distinct property in 1-to-1 messaging channels to reuse the same channel when a user chooses to directly message a friend. If the property is turned off, a new channel is created with the same friend even if there is a previous conversation between them, and you can't see previously sent messages or data.

GroupChannel.createChannelWithUserIds(USER_IDS, IS_DISTINCT, new GroupChannel.GroupChannelCreateHandler() {
    @Override
    public void onResult(GroupChannel groupChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can also append information by passing additional arguments.

GroupChannel.createChannel(USER_IDS, IS_DISTINCT, NAME, COVER_IMAGE_OR_URL, DATA, CUSTOM_TYPE, HANDLER)
  • NAME: the name of a channel, or the channel topic.
  • COVER_IMAGE_OR_URL: the file or URL of the cover image, which you can fetch to render into the UI.
  • DATA: the String field to store structured information, such as a JSON String.
  • CUSTOM_TYPE: the String field that allows you to subclassify your channel.

Note: See the Advanced section for more information on cover images and custom types.

You can also create channels via the SendBird Platform API. If you want to control channel creations and member invitations on the server-side, use the Platform API.


Getting a group channel instance with a URL

Since a channel URL is a unique identifier of a group channel, you can use a URL to retrieve a channel instance. Store channel URLs to handle lifecycle or state changes in your app. For example, if a user disconnects from SendBird by temporarily switching to another app, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance, then re-entering the user into the channel.

GroupChannel.getChannel(channelUrl, new GroupChannel.GroupChannelGetHandler() {
    @Override
    public void onResult(GroupChannel groupChannel, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }

        // Successfully fetched the channel.
        // Do something with groupChannel.
    }
});

Inviting users to an existing channel

Only members of the channel can invite new users into the channel. You can determine whether the newly invited user sees the past messages in the channel or not. In your Dashboard Settings - Messages section, there is an option to show channel history. If this option is turned on, new users can view all messages sent before they have joined the channel. If not, new users can see only messages sent after they have been invited.

Note: By default, Show channel history is turned on.

groupChannel.inviteWithUserIds(userIds, new GroupChannel.GroupChannelInviteHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Leaving the group channel

If a user leaves the group channel, the user can't receive messages from the channel anymore.

groupChannel.leave(new GroupChannel.GroupChannelLeaveHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Getting a list of my group channels

You can obtain a list of all group channels by creating a GroupChannelListQuery. The next() method returns a list of GroupChannel objects.

Note: You can also set an option to include empty channels with setIncludeEmpty(boolean). Empty channels are channels that have been created but contain no sent messages. By default, empty channels are not shown.

GroupChannelListQuery channelListQuery = GroupChannel.createMyGroupChannelListQuery();
channelListQuery.setIncludeEmpty(true);
channelListQuery.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
    @Override
    public void onResult(List<GroupChannel> list, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Querying group channels by User IDs

It is possible to filter a channel search by user IDs. This can be done by calling setUserIdsExactFilter(List<String> userIds) or setUserIdsIncludeFilter(List<String> userIds, QueryType queryType).

Given an example where a user (with the ID "User") is part of two group channels:

  • channelA: [ "User", "John", "Jay" ]
  • channelB: [ "User", "John", "Jay", "Jin" ]

An ExactFilter returns the list of channels containing exactly the queried userIDs.

GroupChannelListQuery filteredQuery = GroupChannel.createMyGroupChannelListQuery();
List<String> userIds = new ArrayList<>();
userIds.add("John");
userIds.add("Jay");

filteredQuery.setUserIdsExactFilter(userIds);
filteredQuery.next(
...
    // returns channelA only.
)

An IncludeFilter returns channels where the userIDs are included. This method returns one of two different results, based on the parameter queryType.

GroupChannelListQuery filteredQuery = GroupChannel.createMyGroupChannelListQuery();
List<String> userIds = new ArrayList<>();
userIds.add("John");
userIds.add("Jay");
userIds.add("Jin");

filteredQuery.setUserIdsIncludeFilter(userIds, GroupChannelListQuery.QueryType.AND);
filteredQuery.next(
...
    // Returns only channelB that include the ids { John, Jay, Jin } as a subset.
)

filteredQuery.setUserIdsIncludeFilter(userIds, GroupChannelListQuery.QueryType.OR);
filteredQuery.next(
...
    // Returns channelA and channelB that include { John }, plus channelA and channelB that include { Jay }, plus channelB that include { Jin }.
    // Actually channelA and channelB are returned.
)

Sending messages

Upon entering a channel, a user can send messages of the following types:

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.

You can additionally specify a CUSTOM_TYPE to further subclassify a message. When you send a text message, you can additionally attach arbitrary strings via a data field. You can utilize this field to send structured data such as font size, font type, or a custom JSON object.

Delivery failures due to the network issues return an exception. By overriding the onSent() callback within an implementation of sendUserMessage(), it is possible to display only the messages that are successfully sent.

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

A user can also send any binary file through SendBird. There are two ways in which you can send a binary file: by sending the file itself, or by sending a URL.

By sending a raw file, you are uploading it to the SendBird servers. Alternatively, you can choose to send a file hosted in your own servers by passing in a URL that points to the file. In this case, your file is hosted in the SendBird servers, and downloaded through your own servers instead.

Note: If you upload your file directly, a size limit is imposed per file. This limit depends on your plan, and can be viewed from your Dashboard. No file size limit is imposed if you send a file message via a URL. Then the file isn't uploaded to the SendBird servers.

// Sending file message with raw file
channel.sendFileMessage(FILE, NAME, TYPE, SIZE, DATA, CUSTOM_TYPE, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

// Sending file message with file URL
channel.sendFileMessage(FILE_URL, NAME, TYPE, SIZE, DATA, CUSTOM_TYPE, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Note: To send metadata along with a file, you can populate the DATA field.


Receiving messages

Messages can be received by adding a ChannelHandler. A received BaseMessage object is one of the following three message types.

  • UserMessage: text message sent by user.
  • FileMessage: binary message sent by user.
  • AdminMessage: message sent by an admin through the Platform API.

UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        if (baseMessage instanceof UserMessage) {
            // message is a UserMessage
        } else if (baseMessage instanceof FileMessage) {
            // message is a FileMessage
        } else if (baseMessage instanceof AdminMessage) {
            // message is an AdminMessage
        }
    }
});

If the UI isn't valid anymore, remove the channel handler.

SendBird.removeChannelHandler(UNIQUE_HANDLER_ID);

Loading previous messages

You can load previous messages by creating a PreviousMessageListQuery instance and calling load(). You can display these messages in your UI once they have loaded.

Note: Whether a user can load messages prior to joining the channel depends on your settings. In your Dashboard Settings - Messages section, there is an option to show channel history. If this option is turned on, new users can view all messages sent before they have joined the channel. If not, new users can see only messages sent after they have been invited.

PreviousMessageListQuery prevMessageListQuery = groupChannel.createPreviousMessageListQuery();
prevMessageListQuery.load(30, true, new PreviousMessageListQuery.MessageListQueryResult() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Past messages are queried in fixed numbers (30 in the above code). A new PreviousMessageListQuery instance loads the most recent n messages. The load() on the same query instance returns n messages before that. So if you store your query instance as a member variable, you can traverse through your entire message history.

Note: Before invoking load() again, you must receive onResult() callback first.


Loading messages by timestamp

You can retrieve a set number of messages starting from a specific timestamp. To load messages sent prior to a specifed timestamp, use channel.getPreviousMessagesByTimestamp().

channel.getPreviousMessagesByTimestamp(timestamp, isInclusive,
        prevResultSize, reverse, messageType, customType,
        new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> list, SendBirdException e) {
        if (e != null) {
            return;
        }

        // Successfully fetched list of messages sent before timestamp.
    }
});
  • timestamp: the reference timestamp.
  • isInclusive: whether to include messages sent exactly at timestamp.
  • prevResultSize: the number of messages to load. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the earliest message.
  • reverse: whether to reverse the results.
  • messageType: a BaseChannel.MessageTypeFilter object. Possible values are limited to MessageTypeFilter.USER, MessageTypeFilter.FILE, MessageTypeFilter.ADMIN, or MessageTypeFilter.ALL.
  • customType: the custom type of the messages to be returned.

To load messages sent after a specified timestamp, call channel.getNextMessagesByTimestamp() in a similar fashion. To load results on either side of the reference timestamp, use channel.getPreviousAndNextMessagesByTimestamp().


Deleting messages

Users can delete messages. An error is returned if a user tries to delete messages sent by someone else. Also channel operators can delete any message in the channel, including those by other users.

Deleting a message fires a MessageDeleted event to all other users in the channel.

channel.deleteMessage(BASE_MESSAGE, new BaseChannel.DeleteMessageHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can receive a MessageDeleted event using a ChannelHandler.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageDeleted(BaseChannel baseChannel, long messageId) {
    }
});

Group Channel: 1-to-1 Chat

A 1-to-1 chat is just a group channel with two members.


Creating a 1-to-1 chat

A group channel can be created on demand by a user through the client SDK. Pass in two user IDs to create a 1-to-1 chat between two users.

You typically want a 1-to-1 chat to be Distinct. If the Distinct property is turned off, a user can create a new channel with the same friend even if there is a previous conversation between them. In this case, multiple 1-to-1 chats between the same two users can exist, each with its own chat history and data.

GroupChannel.createChannelWithUserIds(USER_IDS, IS_DISTINCT, new GroupChannel.GroupChannelCreateHandler() {
    @Override
    public void onResult(GroupChannel groupChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can also append information within the channel by passing additional arguments.

GroupChannel.createChannel(USER_IDS, IS_DISTINCT, NAME, COVER_IMAGE_OR_URL, DATA, CUSTOM_TYPE, HANDLER)
  • NAME: the name of a channel, or the channel topic.
  • COVER_IMAGE_OR_URL: the file or URL of the cover image, which you can fetch to render into the UI.
  • DATA: the String field to store structured information, such as a JSON String.
  • CUSTOM_TYPE: the String field that allows you to subclassify your channel.

Note: See the Advanced section for more information on cover images and Custom Types.

You can also create channels via the SendBird Platform API. If you want to control channel creations and member invitations on the server-side, use the Platform API.

Group Channel: Advanced

This section explains the premium features of Group Channel. Some are available only to a paying user.


Getting a list of all channel members

You can obtain a list of members in a group channel using getMembers().

List<User> members = groupChannel.getMembers();

Members are automatically updated when you are online. If you disconnect from SendBird and reconnect, you must refresh() the channel to be updated with the latest information.

groupChannel.refresh(new GroupChannel.GroupChannelRefreshHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            //Error.
            return;
        }
    }
});

Getting members' online statuses

To stay updated on each member's connection status, call channel.refresh() before calling channel.getMembers(). You can then check each of the users' connection statuses by making calls to user.getConnectionStatus().

Note: If your app needs to keep track of users' connection statuses in real time, we recommend you to refresh() your channel instance periodically, perhaps in intervals of one minute or more.

getConnectionStatus() returns one of three values:

  • User.ConnectionStatus.NON_AVAILABLE: user's status information cannot be reached.
  • User.ConnectionStatus.OFFLINE: user is disconnected from SendBird.
  • User.ConnectionStatus.ONLINE: user is connected to SendBird.

Typing indicators

You can send typing events by invoking startTyping and endTyping.

groupChannel.startTyping();
groupChannel.endTyping();

You can receive a TypingStatusUpdate event in the channel handler.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onTypingStatusUpdated(GroupChannel groupChannel) {
        if (currentGroupChannel.getUrl().equals(groupChannel.getUrl())) {
            List<User> members = groupChannel.getTypingMembers();
            // Refresh typing status of members within channel.
        }
    }
});

Read receipts

A user can indicate that they have read a message by calling markAsRead().

groupChannel.markAsRead();

This broadcasts a ReadReceiptUpdate event, which can be handled with a ChannelHandler.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onReadReceiptUpdated(GroupChannel groupChannel) {
        if (currentGroupChannel.getUrl().equals(groupChannel.getUrl())) {
            for (BaseMessage msg : yourMessages) {
                int unreadCount = groupChannel.getReadReceipt(msg);
                if (unreadCount <= 0) {
                    // All members have read the message.
                } else {
                    // Some members haven't read the message.
                }
            }
        }
    }
});

getReadReceipt(BaseMessage) returns the number of members in the channel who have not read the message.

  int unreadCount = groupChannel.getReadReceipt(message);

Viewing who has read a message

You can view who has read a message with channel.getReadMembers(message). This list is updated when the message's read receipt is updated. Therefore, you must replace your previous message instance with the newly received message in onReadReceiptUpdate() for real-time updates.

List<User> readMembers = channel.getReadMembers(message);

Similarly, you can also view who has not read the message with channel.getUnreadMembers(message).


Admin messages

You can send an admin message to users in a channel using the SendBird Dashboard or the Platform API. To send the admin message via the Dashboard, in the Group Channels panel, select a group channel, find a message box below, click the Admin Message tab, and write a message in the box. The admin message is limited to 1000 characters.

If you are currently developing under the Free Plan and therefore cannot use the Moderation Tools from the Dashboard, you must send the admin messages through the Platform API.


Channel cover images

When creating a channel, you can add a cover image by specifying an image URL or file.

GroupChannel.createChannel(NAME, COVER_URL, DATA, new GroupChannel.GroupChannelCreateHandler() {
    @Override
    public void onResult(GroupChannel groupChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can get the cover image URL using getCoverUrl(). You can also update a channel's cover image by calling updateChannel().


Custom channel types

When creating a channel, you can additionally specify a custom type to further subclassify your channels. This custom type takes on the form of a String, and can be handy in searching or filtering channels.

Note: DATA and CUSTOM_TYPE are both String fields that allow you to append information to your channels. The use case is for CUSTOM_TYPE to contain information that can subclassify the channel (for example, distinguishing "School" and "Work" channels). However, both these fields can be flexibly utilized.

GroupChannel.createChannel(NAME, COVER_URL, DATA, CUSTOM_TYPE new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(GroupChannel groupChannel, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

To get a channel's custom type, call channel.getCustomType().


Custom message types

Likewise, you can specify a custom type for messages to categorize them into more specific groups. This custom type takes on the form of a String, and can be useful in searching or filtering messages.

Note: DATA and CUSTOM_TYPE are both String fields that allow you to append information to your messages. The use case is for CUSTOM_TYPE to contain information that can subclassify the message (for example, distinguishing "FILE_IMAGE" and "FILE_AUDIO" type messages). However, both these fields can be flexibly utilized.

To embed a custom type into a message, pass a String parameter to channel.sendUserMessage() or channel.sendFileMessage().

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

To get a message's custom type, call message.getCustomType().


Message auto-translation

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

SendBird makes it possible for messages to be sent in different languages through its auto-translation feature. Pass in a List of language codes to sendUserMessage() to request translated messages in the corresponding languages.

ArrayList targetLangList = new ArrayList<String>();
targetLangList.add("es");
targetLangList.add("ko");

channel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, targetLangList, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

You can obtain translations of a message using userMessage.getTranslations(). This method returns a Map containing the language codes and translations.

SendBird.addChannelHandler(UNIQUE_CHANNEL_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        Map<String, String> map = ((UserMessage) baseMessage).getTranslations();
        String esTranslation = map.get("es");
        ...
        // Display translation in UI.
    }
}

Note: The message auto-translation supports 53 languages. For the language code table, see the Miscellaneous > Supported Languages.


File message thumbnails

This feature is not available under the Free plan. Contact sales@sendbird.com if you want to implement this functionality.

When sending an image file, you can choose to create thumbnails of the image, which you can fetch and render into your UI. You can specify up to 3 different dimensions to generate thumbnail images in, which can be convenient for supporting various display densities.

Note: Supported file types are files whose media type is image/* or video/*. The SDK does not support creating thumbnails when sending a file message via a file URL.

Create a List of FileMessage.ThumbnailSize objects to pass to channel.sendFileMessage(). A ThumbnailSize can be created with the constructor ThumbnailSize(int maxWidth, int maxHeight), where the values specify pixels. The onSent() callback subsequently returns a List of Thumbnail objects that each contain the URL of the generated thumbnail image file.

List<FileMessage.ThumbnailSize> thumbnailSizes = new ArrayList<>();

// Create and add ThumbnailSizes (Max: 3 ThumbnailSizes).
thumbnailSizes.add(new ThumbnailSize(100, 100));
thumbnailSizes.add(new ThumbnailSize(200, 200)); 

channel.sendFileMessage(file, name, type, size, data, customtype, thumbnailSizes, new BaseChannel.SendFileMessageHandler() {
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Error!
        }

        Thumbnail first = fileMessage.getThumbnails.get(0);
        Thumbnail second = fileMessage.getThumbnails.get(1);

        int maxHeightFirst = first.getMaxHeight(); // 100
        int maxHeightSecond = second.getMaxHeight(); // 200

        String urlFirst = first.getUrl(); // URL of first thumbnail file.
        String urlSecond = second.getUrl(); // URL of second thumbnail file.
    }
}

Channel Metadata

With metadata and metacounter, you can store additional information within a channel. The Metadata allows you to store a Map of String key-value pairs in a channel instance. If you want to store an integer with atomic increasing and decreasing operations, use the metacounter instead.

Use cases for metadata/matacounters are such as tracking the number of likes, the background color, or a long description of the channel, which can each be fetched and rendered into the UI.


Metadata

Metadata is a map that is stored within a channel. Its uses are very flexible, allowing you to customize a channel to fit you and your users' needs.

Create

To store metadata into a channel, create a Map, and then pass it as an argument when calling createMetaData(). You can store multiple key-value pairs in the map.

HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");

channel.createMetaData(data, new BaseChannel.MetaDataHandler() {
    @Override
    public void onResult(Map<String, String> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Update

The process for updating metadata is identical with the creation. Values are updated for existing keys, while new key-value pairs added.

HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "valueToUpdate");
data.put("key2", "valueToUpdate");

channel.updateMetaData(data, new BaseChannel.MetaDataHandler() {
    @Override
    public void onResult(Map<String, String> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Get

To get stored metadata, create Collection of keys, and then pass it as an argument to getMetaData(). The callback onResult() returns a Map<String, String> containing the corresponding key-value pairs.

List<String> keys = new ArrayList<String>();
keys.add("key1");
keys.add("key2");

channel.getMetaData(keys, new BaseChannel.MetaDataHandler() {
    @Override
    public void onResult(Map<String, String> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Metacounter

A metacounter is a map that is stored within a channel instance. Its primary uses are to track and update discrete indicators within a channel.

Create

To store a metacounter into a channel, create a Map, and then pass it as an argument when calling createMetaCounter(). You can store multiple key-value pairs in the map.

HashMap<String, Integer> counters = new HashMap<String, Integer>();
counters.put("key1", 1);
counters.put("key2", 2);

channel.createMetaCounters(counters, new BaseChannel.MetaCounterHandler() {
    @Override
    public void onResult(Map<String, Integer> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Get

To get stored metacounters, create a Collection of keys, and then pass it as an argument to getMetaCounters(). The callback onResult() returns a Map<String, Integer> containing the corresponding key-value pairs.

List<String> keys = new ArrayList<String>();
keys.add("key1");
keys.add("key2");

channel.getMetaCounters(keys, new BaseChannel.MetaCounterHandler() {
    @Override
    public void onResult(Map<String, Integer> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Increase

The increase and decrease operations work similarly to getting metacounters, as described above. Create a Collection of keys to pass to increaseMetaCounters(), which increments the corresponding metacounters by 1.

HashMap<String, Integer> counters = new HashMap<String, Integer>();
counters.put("key1", 2); // Increases by 2.
counters.put("key2", 3); // Increases by 3.

channel.increaseMetaCounters(counters, new BaseChannel.MetaCounterHandler() {
    @Override
    public void onResult(Map<String, Integer> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Decrease

Pass a Collection of keys to decreaseMetaCounters(), which decrements the metacounters by 1.

HashMap<String, Integer> counters = new HashMap<String, Integer>();
counters.put("key1", 3); // Decreases by 3.
counters.put("key2", 4); // Decreases by 4.

channel.decreaseMetaCounters(counters, new BaseChannel.MetaCounterHandler() {
    @Override
    public void onResult(Map<String, Integer> map, SendBirdException e) {
        if (e != null) {
            // Error.
            return;
        }
    }
});

Event Handler

Event Handlers are crucial components of the SendBird SDK that allow a client to react to server-side events. These handlers contain callback methods that can be overridden to respond to specific chat-related events passed from the server. For example, ChannelHandler.onMessageReceived(BaseChannel, BaseMessage) is triggered whenever a message is received. The specifics of each received message is contained within the BaseChannel and BaseMessage arguments passed in the triggering callback.

By providing its own Event Handlers, the SendBird SDK allows a client to respond to asynchronous events without worrying about the plethora of issues surrounding client-server communication and multithreading. A chat application especially involves rapid exchanges of data that must take place in near real-time across potentially thousands of users. Therefore, the SDK optimizes communication and threading to ensure data integrity between users and servers. Add Event Handlers and implement the necessary callback methods to track events occurring within channels or a user's own device.


Channel Handler

Register a ChannelHandler to receive information whenever events occur within a channel. You can register multiple channel handlers. UNIQUE_HANDLER_ID is a unique identifier given to each handler. Typically, Event Handlers is registered in each activity to stay up to date with changes in the channel, as well as notify the channel of the user's own activity.

SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        // Received a chat message.
    }

    @Override
    public void onMessageDeleted(BaseChannel baseChannel, long messageId) {
      // When a message has been deleted.
    }

    @Override
    public void onChannelChanged(BaseChannel baseChannel) {
      // When a channel property has been changed.
      // More information on the properties can be found below.
    }

    @Override
    public void onChannelDeleted(String channelUrl, BaseChannel.ChannelType channelType) {
      // When a channel has been deleted.
    }

    @Override
    public void onReadReceiptUpdated(GroupChannel groupChannel) {
        // When read receipt has been updated.
    }

    @Override
    public void onTypingStatusUpdated(GroupChannel groupChannel) {
        // When typing status has been updated.
    }

    @Override
    public void onUserJoined(GroupChannel groupChannel, User user) {
      // When a new member joined the group channel.
    }

    @Override
    public void onUserLeft(GroupChannel groupChannel, User user) {
      // When a member left the group channel.
    }

    @Override
    public void onUserEntered(OpenChannel openChannel, User user) {
      // When a new user entered the open channel.
    }

    @Override
    public void onUserExited(OpenChannel openChannel, User user) {
      // When a new user left the open channel.
    }

    @Override
    public void onUserMuted(OpenChannel openChannel, User user) {
      // When a user is muted on the open channel.
    }

    @Override
    public void onUserUnmuted(OpenChannel openChannel, User user) {
      // When a user is unmuted on the open channel.
    }

    @Override
    public void onUserBanned(OpenChannel openChannel, User user) {
      // When a user is banned on the open channel.
    }

    @Override
    public void onUserUnbanned(OpenChannel openChannel, User user) {
      // When a user is unbanned on the open channel.
    }

    @Override
    public void onChannelFrozen(OpenChannel openChannel) {
      // When the open channel is frozen.
    }

    @Override
    public void onChannelUnfrozen(OpenChannel openChannel) {
      // When the open channel is unfrozen.
    }
});

onChannelChanged() is called whenever a one of the following channel properties have been changed :

  • Push preference
  • Last message (except in cases where the message is a silent Admin message)
  • Unread message count
  • Name, cover image, data, custom type
  • Operators (only applicable to open channels)
  • Distinct property (only applicable to group channels)

If the activity isn't valid anymore, remove the channel handler.

SendBird.removeChannelHandler(UNIQUE_HANDLER_ID);

Connection Handler

Register a ConnectionHandler to detect changes in the user's own connection status. You can register multiple connection handlers. UNIQUE_HANDLER_ID is a unique identifier that given to each handler. Typically, the connection handlers are registered in each activity to monitor the state of the user's connection with the SendBird servers.

SendBird.addConnectionHandler(UNIQUE_HANDLER_ID, new SendBird.ConnectionHandler() {
    @Override
    public void onReconnectStarted() {
        // Network has been disconnected. Auto reconnecting starts.
    }

    @Override
    public void onReconnectSucceeded() {
        // Auto reconnecting succeeded.
    }

    @Override
    public void onReconnectFailed() {
        // Auto reconnecting failed. Call `connect` to reconnect to SendBird.
    }
});

If the activity isn't valid anymore, remove the connection handler.

SendBird.removeConnectionHandler(UNIQUE_HANDLER_ID);

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 turn on the push notifications for Android.

  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 that calls SendBird.connect().

SendBird.connect(userId, 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
  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
  },
  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.
        }
    }
});

Caching Data

Storing a local copy of SendBird data in a device helps users look through their messages and channels even while offline. It can also prevent the inefficiency of repeating queries upon each connection or device state change, as well as provide a smoother user experience by reducing data loading delays.

In this document, we show you how to build a local cache using object serialization/deserialization, which is provided through the SDK. In the Basic caching using a file section, we provide instructions on building a simple cache that stores the most recent messages and channels in a file. In the Advanced caching using a database section, you can find instructions on caching data in an internal database, which helps you store structured and queriable data.

Basic caching using a file

This section shows you how to build a simple cache that stores a user's most recent messages and channels. This cache can be used to load data when a user views their channel list, or enters a channel to view their message history. Implementing even a basic cache such as this can greatly improve user experience, as users no longer encounter empty lists of channels or messages when their connectivity is unstable.

In the steps described below, we create a file per channel in the application's cache directory, write serialized data into the file to store a set amount of recent messages, configure the app to first load messages from the cache, and then finally replace them when the newest results are successfully fetched from the servers.


Object serialization / deserialization

To store SendBird objects such as messages, channels, and users in local storage, we provide serialization and deserialization methods through our SDK. Use serialize() to convert a SendBird object to binary data, which can then be natively stored in a file.

byte[] baseMessage.serialize()
BaseMessage BaseMessage.buildFromSerializedData(byte[] data)

byte[] baseChannel.serialize()
BaseChannel BaseChannel.buildFromSerializedData(byte[] data)

Saving messages

With serialization, you can store a channel and its most recent messages in a file. In this case, we are encoding the binary serialized data into a Base64 string. then storing each item in a new line. Normally, save data when onStop() is called in your user's chat screen.

public void save() {
    try {
        StringBuilder sb = new StringBuilder();
        if (mChannel != null) {
            // Convert current channel instance into a string.
            sb.append(Base64.encodeToString(mChannel.serialize(), Base64.DEFAULT | Base64.NO_WRAP));

            // Converts up to 100 messages within the channel into a string.
            BaseMessage message = null;
            for (int i = 0; i < Math.min(mMessageList.size(), 100); i++) {
                message = mMessageList.get(i);
                sb.append("\n");
                sb.append(Base64.encodeToString(message.serialize(), Base64.DEFAULT | Base64.NO_WRAP));
            }

            String data = sb.toString();
            String md5 = TextUtils.generateMD5(data);

            // Create a file within the app's cache directory.
            File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
            appDir.mkdirs();

            // Create a data file and a hash file within the directory.
            File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + mChannel.getUrl()) + ".data");
            File hashFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + mChannel.getUrl()) + ".hash");

            try {
                String content = FileUtils.loadFromFile(hashFile);
                // If data has not been changed, do not save.
                if(md5.equals(content)) {
                    return;
                }
            } catch(IOException e) {
                // File not found. Save the data.
            }

            FileUtils.saveToFile(dataFile, data);
            FileUtils.saveToFile(hashFile, md5);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

Note: In this case, MD5 hashing is used to generate a hash file for each stored data file. Using this hash file, you can check if the newly generated data differs from the one already stored in the cache, preventing unnecessary overwriting.


Loading messages

When your user enters a chat to view their message history, load saved messages from the cache.

public void load(String channelUrl) {
    try {
        File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
        appDir.mkdirs();

        File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + channelUrl) + ".data");

        String content = FileUtils.loadFromFile(dataFile);
        String [] dataArray = content.split("\n");

        // Load the channel instance.
        mChannel = (GroupChannel) GroupChannel.buildFromSerializedData(Base64.decode(dataArray[0], Base64.DEFAULT | Base64.NO_WRAP));

        // Add the loaded messages to the currently displayed message list.
        for(int i = 1; i < dataArray.length; i++) {
            mMessageList.add(BaseMessage.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
        }

        notifyDataSetChanged();
    } catch(Exception e) {
        // Nothing to load.
    }
}

After receiving an updated message list from the SendBird servers, clear the current message list and replace it with the updated list. In effect, messages from the cache are overwritten almost instantly if the user's connection is normal.


Saving and loading channels

The process of caching channels is identical to caching messages. For the sake of brevity, an implementation is provided without additional explanations.

// Saving channels
public void save() {
    try {
        StringBuilder sb = new StringBuilder();
        if (mChannelList != null && mChannelList.size() > 0) {
            // Convert current channel into a String.
            GroupChannel channel = null;
            for (int i = 0; i < Math.min(mChannelList.size(), 100); i++) {
                channel = mChannelList.get(i);
                sb.append("\n");
                sb.append(Base64.encodeToString(channel.serialize(), Base64.DEFAULT | Base64.NO_WRAP));
            }
            // Remove first newline.
            sb.delete(0, 1);

            String data = sb.toString();
            String md5 = TextUtils.generateMD5(data);

            // Save the data into file.
            File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
            appDir.mkdirs();

            File hashFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".hash");
            File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");

            try {
                String content = FileUtils.loadFromFile(hashFile);
                // If data has not been changed, do not save.
                if(md5.equals(content)) {
                    return;
                }
            } catch(IOException e) {
                // File not found. Save the data.
            }

            FileUtils.saveToFile(dataFile, data);
            FileUtils.saveToFile(hashFile, md5);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

// Loading channels
public void load() {
    try {
        File appDir = new File(mContext.getCacheDir(), SendBird.getApplicationId());
        appDir.mkdirs();

        File dataFile = new File(appDir, TextUtils.generateMD5(SendBird.getCurrentUser().getUserId() + "channel_list") + ".data");

        String content = FileUtils.loadFromFile(dataFile);
        String [] dataArray = content.split("\n");

        // Add the loaded channels to the currently displayed channel list.
        for(int i = 0; i < dataArray.length; i++) {
            mChannelList.add((GroupChannel) BaseChannel.buildFromSerializedData(Base64.decode(dataArray[i], Base64.DEFAULT | Base64.NO_WRAP)));
        }

        notifyDataSetChanged();
    } catch(Exception e) {
        // Nothing to load.
    }
}

Advanced caching using a database

This section shows you how to build your own local cache using a database. This has several advantages like storing raw data in a file and enabling queries on stored channels and messageso particularly. Our examples are written based on the SQLite, it's not difficult to follow these steps with any database of your choice, such as Realm.


Object serialization / deserialization

To store SendBird objects such as messages, channels, and users in local storage, we provide serialization and deserialization methods through our SDK. Use serialize() to convert a SendBird object to binary data, which can then be natively stored in your persistent database.

byte[] baseMessage.serialize()
BaseMessage BaseMessage.buildFromSerializedData(byte[] data)

Caching messages

Table structure

A basic table to store messages contains the following columns:

message_id channel_url message_ts payload
123123 sendbird_channel_234802384 1432039402823 Serialized data
234234 sendbird_channel_234802384 1432039403417 Serialized data

Caching procedure

  1. After fetching new messages using a MessageListQuery, serialize and insert each message into your database. However, we recommend to store the message ID, timestamp, and channel URL in separate columns by using message.getMessageId(), message.getCreatedAt(), and message.getChannelUrl(). This allows you to query the dataset later on.

  2. Before loading messages within a channel, order rows chronologically by message_ts. Then, deserialize each message and display them in your UI.

  3. When loading previous messages that are not currently stored in the local database, obtain the timestamp of the earliest stored message. Then, query for messages created before that value.

  4. Likewise, when loading new messages, query for messages with a later timestamp than the most recent message.

Example 1: When entering a channel
// Get messages from local database
final SQLiteDatabase database = dbHelper.getWritableDatabase();

String selection = COLUMN_NAME_CHANNEL_URL + " = ?";
String[] selectionArgs = { CURRENT_CHANNEL_URL };

String sortOrder = COLUMN_NAME_TIMESTAMP + " DESC";

Cursor cursor = database.query(
        TABLE_NAME,
        null, // The columns to return; all if null.
        selection, // The columns for the WHERE clause
        selectionArgs, // The values for the WHERE clause
        null, // Don't group the rows
        null, // Don't filter by row groups
        sortOrder, // The sort order
        "30" // The limit
);

// Create a List of BaseMessages by deserializing each item.
List<BaseMessage> prevMessageList = new ArrayList<>();

while (cursor.moveToNext()) {
    byte[] data = cursor.getBlob(cursor.getColumnIndex(COLUMN_NAME_PAYLOAD));
    BaseMessage message = BaseMessage.buildFromSerializedData(data);
    prevMessageList.add(message);
}

cursor.close();

// Pass messages to adapter for displaying them in a RecyclerView, ListView, etc.
mMessageListAdapter.addMessages(prevMessageList);

// Get new messages from the SendBird servers
long latestStoredTs = prevMessageList.get(0).getCreatedAt(); // Get the timestamp of the last stored message.
MessageListQuery query = mChannel.createMessageListQuery();
query.next(latestStoredTs, 30, false, new MessageListQuery.MessageListQueryResult() {
    @Override
    public void onResult(List<BaseMessage> list, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }
        // New messages successfully fetched.
        mMessageListAdapter.addMessages(list);

        // Insert each new message in your local database
        for (BaseMessage message : list) {
            // Store each new message into the local database
            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME_ID, message.getMessageId());
            values.put(COLUMN_NAME_CHANNEL_URL, message.getChannelUrl());
            values.put(COLUMN_NAME_TIMESTAMP, message.getCreatedAt());
            values.put(COLUMN_NAME_PAYLOAD, message.serialize());

            database.insert(TABLE_NAME, null, values);
        }
    }
});

database.close();
Example 2: When receiving new messages
SendBird.addChannelHandler(CHANNEL_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
        if (baseChannel.getUrl().equals(mChannelUrl)) {
            // Pass the message to your adapter.
            mMessageListAdapter.addMessage(baseMessage);

            // Store the message in your local database.
            // It is a good idea to have a helper class or method for database transactions.
            final SQLiteDatabase database = dbHelper.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME_ID, baseMessage.getMessageId());
            values.put(COLUMN_NAME_CHANNEL_URL, baseMessage.getChannelUrl());
            values.put(COLUMN_NAME_TIMESTAMP, baseMessage.getCreatedAt());
            values.put(COLUMN_NAME_PAYLOAD, baseMessage.serialize());

            database.insert(TABLE_NAME, null, values);

            database.close();
        }
    }
});
Example 3: When sending a message
mChannel.sendUserMessage(messageBody, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }

        // Display sent message to RecyclerView
        mMessageListAdapter.addMessage(userMessage);

        // Store the message in your local database.
        // It is a good idea to have a helper class or method for database transactions.
        final SQLiteDatabase database = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_ID, userMessage.getMessageId());
        values.put(COLUMN_NAME_CHANNEL_URL, userMessage.getChannelUrl());
        values.put(COLUMN_NAME_TIMESTAMP, userMessage.getCreatedAt());
        values.put(COLUMN_NAME_PAYLOAD, userMessage.serialize());

        database.insert(TABLE_NAME, null, values);

        database.close();
    }
});

Caveats

Currently, it is difficult to sync deleted or edited messages. We are working to provide this feature in both our SDKs and APIs, and hope to release it soon.


Caching channels

Note: The examples in this section are based on Group Channel. To cache Open Channel, slightly improvise from the directions below (such as changing last_message_ts to channel_created_at).

Table structure

A basic table to store channels contains the following columns:

channel_url last_message_ts payload
sendbird_channel_234802384 1432039402416 Serialized data
sendbird_channel_234802384 1432039403610 Serialized data

Caching procedure

  1. After fetching new channels using a OpenChannelListQuery or GroupChannelListQuery, serialize and insert each channel into your database. As with messages, we recommend to store the channel URL and timestamp of the last message in separate columns by using channel.getUrl() and channel.getLastMessage().getCreatedAt(). This allows you to query the dataset later on.

  2. Before loading a list of channels, order rows chronologically by last_message_ts. Then, deserialize each channel and display them in your UI.

  3. Unlike messages, channels are relatively few in number and go through frequent property changes, such as cover URL changes, name changes, or deletions. Therefore, we recommend updating your cache by completely replacing the dataset when possible.

  4. When real-time changes are made to a channel list, update your cache.

Example 1: When entering the channel list screen
// Load channels from local database
final SQLiteDatabase database = dbHelper.getWritableDatabase();

String sortOrder = COLUMN_NAME_LAST_MESSAGE_TIMESTAMP + " DESC";

Cursor cursor = database.query(
        TABLE_NAME,
        null, // The columns to return; all if null.
        null, // The columns for the WHERE clause
        null, // The values for the WHERE clause
        null, // Don't group the rows
        null, // Don't filter by row groups
        sortOrder, // The sort order
        "30" // The limit
);

// Create a List of BaseChannels by deserializing each item.
final List<BaseChannel> prevChannelList = new ArrayList<>();

while (cursor.moveToNext()) {
    byte[] data = cursor.getBlob(cursor.getColumnIndex(COLUMN_NAME_PAYLOAD));
    BaseChannel channel = BaseChannel.buildFromSerializedData(data);
    prevChannelList.add(channel);
}

cursor.close();

// Pass channels to adapter to display them in a RecyclerView, ListView, etc.
mChannelListAdapter.addChannels(prevChannelList);

// Get new channels from the SendBird servers
GroupChannelListQuery query = GroupChannel.createMyGroupChannelListQuery();
query.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
    @Override
    public void onResult(List<GroupChannel> list, SendBirdException e) {
        if (e != null) {
            // Error!
            return;
        }

        // Replace the current (cached) dataset
        mChannelListAdapter.clear();
        mChannelListAdapter.addChannels(prevChannelList);

        // Clear the current cache
        database.delete(TABLE_NAME, null, null);

        // Insert each new channel in your local database
        for (GroupChannel channel : list) {
            // Store each new channel into the local database
            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME_CHANNEL_URL, channel.getUrl());
            values.put(COLUMN_NAME_LAST_MESSAGE_TIMESTAMP, channel.getLastMessage().getCreatedAt());
            values.put(COLUMN_NAME_PAYLOAD, channel.serialize());

            database.insert(TABLE_NAME, null, values);
        }
    }
});

database.close();
}
Example 2: On real-time events such as additions or updates
SendBird.addChannelHandler(CHANNEL_HANDLER_ID, new SendBird.ChannelHandler() {
    ...
    @Override
    public void onChannelChanged(BaseChannel channel) {
        final SQLiteDatabase database = dbHelper.getWritableDatabase();

        String selection = COLUMN_NAME_CHANNEL_URL + " = ?";
        String[] selectionArgs = { CURRENT_CHANNEL_URL };

        // Get the changed channel from the local database using its URL.
        Cursor cursor = database.query(
                TABLE_NAME,
                null, // The columns to return; all if null.
                selection, // The columns for the WHERE clause
                selectionArgs, // The values for the WHERE clause
                null, // Don't group the rows
                null, // Don't filter by row groups
                null, // The sort order
                "1" // The limit
        );

        byte[] data = cursor.getBlob(cursor.getColumnIndex(COLUMN_NAME_PAYLOAD));

        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME_CHANNEL_URL, channel.getUrl());
        long lastMessageTs = ((GroupChannel) channel).getLastMessage().getCreatedAt();
        values.put(COLUMN_NAME_LAST_MESSAGE_TIMESTAMP, lastMessageTs);
        values.put(COLUMN_NAME_PAYLOAD, channel.serialize());

        if (data != null) {
            // If the channel is in the current cache, update it.
            database.update(TABLE_NAME, values, selection, selectionArgs);
        } else {
            // If the channel is not currently cached, add it.
            database.insert(TABLE_NAME, null, values);
        }

        database.close();
    }
});

Note: A similar process can be followed for onChannelDeleted(), onUserJoined(), and onUserLeft().

Miscellaneous

This section contains information for the following:

  • Client error codes
  • Server error codes
  • Supported languages

Client error codes

The following errors that are defined in SendBirdError.java are six-digit integers beginning with 800.

Error Code Description
ERR_INVALID_INITIALIZATION 800100 Initialization failed
ERR_CONNECTION_REQUIRED 800101 Connection required
ERR_INVALID_PARAMETER 800110 Invalid parameters
ERR_NETWORK 800120 Network error
ERR_NETWORK_ROUTING_ERROR 800121 Routing error
ERR_MALFORMED_DATA 800130 Malformed data
ERR_MALFORMED_ERROR_DATA 800140 Malformed error data
ERR_WRONG_CHANNEL_TYPE 800150 Wrong channel type
ERR_MARK_AS_READ_RATE_LIMIT_EXCEEDED 800160 Mark as read rate limit exceeded
ERR_QUERY_IN_PROGRESS 800170 Query is in progress
ERR_ACK_TIMEOUT 800180 Command ack timed out
ERR_LOGIN_TIMEOUT 800190 Login timed out
ERR_WEBSOCKET_CONNECTION_CLOSED 800200 Connection closed
ERR_WEBSOCKET_CONNECTION_FAILED 800210 Connection failed
ERR_REQUEST_FAILED 800220 Request failed

Server error codes

The following errors are six-digit integers beginning with 400, 500, and 900.

Code Description
400100 Parameter Error - String value is required
400101 Parameter Error - Number value is required
400102 Parameter Error - List value is required
400103 Parameter Error - Json value is required
400104 Parameter Error - Boolean value is required
400105 Parameter Error - Not all the required fields are arrived
400106 Parameter Error - Value must be a positive number
400107 Parameter Error - Value must be a negative number
400108 User doesn't have an access to channels or messages
400110 Parameter Error - Length of value is not valid
400111 Parameter Error - Unknown
400112 Parameter Error - Should provide two different values
400151 Parameter Error - Not allowed characters
400201 Object(Channel/User/Message) not found
400202 Unique constraint violation
400300 User Authentication Error - Deactivated user
400301 User Authentication Error - Deleted user or user not found
400302 User Authentication Error - Invalid access token
400303 User Authentication Error - Unexpected error
400304 User Authentication Error - Application not found
400305 User Authentication Error - User id is too long
400306 User Authentication Error - Plan quota exceeded
400307 User Authentication Error - Requests from authorized domain
400601 The push token registration failure
400602 The push token removal failure
400910 Requests are rate-limited
400920 Tried to access non-allowed features under your plan
500901 Unexpected errors
900010 Try to send messages without login
900020 Try to send messages to group channels not belong to the user
900021 Try to send messages after getting deactivated
900030 Try to send messages to the channels when the guest policy is read-only on dashboard
900041 The user is muted on this channel
900050 User cannot send messages to frozen channels
900060 Message is blocked by profanity filter
900070 Try to send messages to deleted channels
900080 You cannot send messages on 1-on-1 group channel when receiver is blocked
900081 You cannot send messages on 1-on-1 group channel when receiver is deactivated
900100 Try to enter the banned channel
900200 You are blocked because you sent too many messages in short period

Supported Languages

SendBird provides message auto-translations for the languages listed in the following table.

Language Code Language Code
Afrikaans af Klingon (pIqaD) tlh-Qaak
Arabic ar Korean ko
Bosnian (Latin) bs-Latn Latvian lv
Bulgarian bg Lithuanian lt
Catalan ca Malay ms
Chinese Simplified zh-CHS Maltese mt
Chinese Traditional zh-CHT Norwegian no
Croatian hr Persian fa
Czech cs Polish pl
Danish da Portuguese pt
Dutch nl Querétaro Otomi otq
English en Romanian ro
Estonian et Russian ru
Finnish fi Serbian (Cyrillic) sr-Cyrl
French fr Serbian (Latin) sr-Latn
German de Slovak sk
Greek el Slovenian sl
Haitian Creole ht Spanish es
Hebrew he Swedish sv
Hindi hi Thai th
Hmong Daw mww Turkish tr
Hungarian hu Ukrainian uk
Indonesian id Urdu ur
Italian it Vietnamese vi
Japanese ja Welsh cy
Kiswahili sw Yucatec Maya yua
Klingon tlh - -

Migration from v2

SDK 3.0 (v3) is a fully innovated chat solution for mobile apps and websites. The structure is elegant and the performance has increased dramatically.

  • OpenChannel and GroupChannel are added for Open Channel and Group Channel related features respectively.
  • UserMessage, FileMessage and AdminMessage are added to handle messages.
  • Callbacks and queries are neatly arranged.

We strongly encourage you in moving to v3 from the previous version and here are the migration tips.


Installation

If you are using gradle, just change the version of dependencies in build.gradle at app level (not project level).

// v2
dependencies {
    compile 'com.sendbird.sdk:sendbird-android-sdk:2.2.16' // 2.2.16 is the latest v2 SDK as of writing this doc.
}

// v3
dependencies {
    compile 'com.sendbird.sdk:sendbird-android-sdk:3.0.4' // 3.0.4 is the latest SDK as of writing this doc.
}

Authentication

Initialization

You still need to initialize SendBird once when your application begins.

// v2
SendBird.init(context, APP_ID);

// v3
SendBird.init(APP_ID, context);

Login

login is no longer used in v3. Calling connect just once after init is all you have to do.

// v2
SendBird.login(LoginOption option);

// v3
SendBird.connect(USER_ID, ConnectHandler handler); // When you allow guest login.
SendBird.connect(USER_ID, ACCESS_TOKEN, ConnectHandler handler); // When you allow only permitted user login.

If you want to update user information such as nickname, profile image or FCM/GCM push tokens, now you can use updateCurrentUserInfo and registerPushTokenForCurrentUser after connection is established.


Open Channel (previous Open Chat Channel)

From v3, we call Open Chat Channel as Open Channel. Members having entered an open channel are referred to as Participants of the channel. OpenChannel and OpenChannelListQuery handle the Open Channel related features.

Getting a list of open channels

// v2
ChannelListQuery channelListQuery = SendBird.queryChannelList();
channelListQuery.next(ChannelListQueryResult handler);

// v3
OpenChannelListQuery channelListQuery = OpenChannel.createOpenChannelListQuery();
channelListQuery.next(OpenChannelListQueryResultHandler handler);

Connecting to an open channel

You don't have to do anything to connect to each open channel in v3. All required connections are automatically made once you have called connect after init. Plus, entering an open channel is much simpler in v3. In v2, you needed to fetch channel URL and call join, queryMessageList and connect.

// v2
SendBird.join(CHANNEL_URL);
SendBird.queryMessageList(CHANNEL_URL).prev(Long.MAX_VALUE, LIMIT, new MessageListQueryResult() {
    @Override
    public void onResult(List<MessageModel> messageModels) {
        // Connect to SendBird with max messages timestamp to receive new messages since last query.
        SendBird.connect(MAX_MESSAGE_TIMESTAMP);
    }

    @Override
    public void onError(Exception e) {
    }
});

// v3
OpenChannel.getChannel(CHANNEL_URL, new OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        openChannel.enter(OpenChannelEnterHandler handler);
    }
});

Disconnecting the open channel

You don't have to do anything to disconnect the open channel in v3. All connections are automatically disconnected when you call disconnect on application termination. If you want a user to leave the open channel, just call exit.

// v2
SendBird.leave(CHANNEL_URL);
SendBird.disconnect();

// v3
OpenChannel.getChannel(CHANNEL_URL, new OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        openChannel.exit(OpenChannelExitHandler handler);
    }
});

Sending messages

Mentioned message is NOT currently supported in v3.

// v2
SendBird.send(MESSAGE);
SendBird.sendWithData(MESSAGE, DATA);

SendBird.uploadFile(FILE, TYPE, SIZE, CUSTOM_FIELD, SendBirdFileUploadEventHandler handler);
FileInfo fileInfo = FileInfo.build(URL_FROM_ABOVE, NAME, TYPE, SIZE, CUSTOM_FIELD);
SendBird.sendFile(fileInfo);

// v3
openChannel.sendUserMessage(MESSAGE, DATA, SendUserMessageHandler handler);
openChannel.sendFileMessage(FILE, FILE_NAME, FILE_TYPE, FILE_SIZE, CUSTOM_DATA, SendFileMessageHandler handler);

Receiving messages

ChannelHandler replaces SendBirdEventHandler. Multiple ChannelHandlers are allowed.

// v2
SendBird.setEventHandler(new SendBirdEventHandler() {
    ...
});

// v3
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
    }
});

Loading previous messages

// v2
SendBird.queryMessageList(SendBird.getChannelUrl()).prev(Long.MAX_VALUE, LIMIT, MessageListQueryResult handler);

// v3
MessageListQuery messageListQuery = openChannel.createMessageListQuery();
messageListQuery.prev(EARLIEST_MESSAGE_TIMESTAMP, LIMIT, REVERSE_ORDER, MessageListQueryResult handler);

Getting a list of all participants in an open channel

Participant means online users in a certain open channel. Once a user leaves the open channel, the user is no longer participant of that channel and query does not include him/her.

// v2
SendBird.queryMemberList(CHANNEL_URL, TRUE_OR_FALSE).get(MemberListQueryResult handler);

// v3
UserListQuery query = openChannel.createParticipantListQuery();
query.next(UserListQueryResultHandler handler);

Group Channel (Previous Messaging Channel)

From v3, we call Messaging Channel as Group Channel. Users joined a group channel are referred to as Members of the channel. GroupChannel and GroupChannelListQuery handle Group Channel related features.

Creating a group channel

All startMessaging related methods are replaced by createChannel and createChannelWithUserIds.

// v2
SendBird.startMessaging(USER_IDS);

// v3
GroupChannel.createChannelWithUserIds(USER_IDS, TRUE_OR_FALSE, GroupChannelCreateHandler handler);

Getting a list of group channels

// v2
MessagingListQuery messagingChannelListQuery = SendBird.queryMessagingChannelList();
messagingChannelListQuery.setLimit(LIMIT);
messagingChannelListQuery.next(MessagingChannelListQueryResult handler);

// v3
GroupChannelListQuery query = GroupChannel.createMyGroupChannelListQuery();
query.setIncludeEmpty(TRUE_OR_FALSE); // If you want to only retrieve channels having previous messages, set this false. 
query.next(GroupChannelListQueryResultHandler handler);

Connecting to a group channel

You don't have to do anything to connect to each group channel in v3. All required connections are automatically made once you have called connect after init.

// v2
SendBird.queryMessageList(CHANNEL_URL).load(Long.MAX_VALUE, PREV_LIMIT, NEXT_LIMIT, new MessageListQueryResult() {
    @Override
    public void onResult(List<MessageModel> messageModels) {
        SendBird.join(CHANNEL_URL);
        SendBird.connect(MAX_MESSAGE_TIMESTAMP);
    }

    @Override
    public void onError(Exception e) {
    }
});

// v3
// Do nothing.

Disconnecting the group channel

You don't have to do anything to disconnect the group channel in v3. All connections are automatically disconnected when you call disconnect on application termination.

// v2
SendBird.disconnect();

// v3
// Do nothing.

Inviting users to an existing channel

// v2
SendBird.inviteMessaging(CHANNEL_URL, USER_ID);

// v3
groupChannel.inviteWithUserIds(USER_IDS, GroupChannelInviteHandler handler);

Removing a user from channel members

// v2
SendBird.endMessaging(CHANNEL_URL);

// v3
groupChannel.leave(GroupChannelLeaveHandler handler);

Sending messages

Mentioned message is NOT currently supported in v3.

// v2
SendBird.send(MESSAGE);
SendBird.sendWithData(MESSAGE, DATA);

SendBird.uploadFile(FILE, TYPE, SIZE, CUSTOM_FIELD, SendBirdFileUploadEventHandler handler);
FileInfo fileInfo = FileInfo.build(URL_FROM_ABOVE, NAME, TYPE, SIZE, CUSTOM_FIELD);
SendBird.sendFile(fileInfo);

// v3
groupChannel.sendUserMessage(MESSAGE, DATA, SendUserMessageHandler handler);
groupChannel.sendFileMessage(FILE, FILE_NAME, FILE_TYPE, FILE_SIZE, CUSTOM_DATA, SendFileMessageHandler handler);

Receiving messages

ChannelHandler replaces SendBirdEventHandler. Multiple ChannelHandlers are allowed.

// v2
SendBird.setEventHandler(new SendBirdEventHandler() {
    ...
});

// v3
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
    }
});

Loading previous messages

// v2
SendBird.queryMessageList(SendBird.getChannelUrl()).prev(Long.MAX_VALUE, LIMIT, MessageListQueryResult handler);

// v3
PreviousMessageListQuery prevMessageListQuery = groupChannel.createPreviousMessageListQuery();
prevMessageListQuery.load(LIMIT, TRUE_OR_FALSE, MessageListQueryResult handler);

Monitoring multiple channels

ChannelHandler replaces SendBirdNotificationHandler. For details, please refer to Event Handler.

// v2
SendBird.registerNotificationHandler(SendBirdNotificationHandler handler);

// v3
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, ChannelHandler handler);

Getting a list of all members

// v2
messagingChannel.getMembers();

// v3
groupChannel.getMembers();

Typing indicators

// v2
SendBird.typeStart();
SendBird.typeEnd();

// v3
groupChannel.startTyping();
groupChannel.endTyping();

Getting read receipt

From v3, various of methods to get read receipt are possible. You can get a timestamp for a certain member just like in v2 or the automatically calculated read receipt as well.

// v2
long timestamp = messagingChannel.getLastReadMillis(USER_ID);

// v3
long timestamp = groupChannel.getLastSeenAtByWithUserId(USER_ID);
int unreadCount = mGroupChannel.getReadReceipt(MESSAGE);

Broadcasting read status

// v2
SendBird.markAsRead();

// v3
groupChannel.markAsRead();

Channel Metadata

Metadata and metacounter can be created, updated and read in v3 by counter parts of methods in v2.

Metadata

// v2
SendBird.queryChannelMetaData(CHANNEL_URL).set(DATA_MAP, ChannelMetaDataQueryResult handler);
SendBird.queryChannelMetaData(CHANNEL_URL).get(KEYS, ChannelMetaDataQueryResult handler);

// v3
channel.createMetaData(DATA_MAP, MetaDataHandler handler);
channel.updateMetaData(DATA_MAP, MetaDataHandler handler);
channel.getMetaData(KEYS, MetaDataHandler handler);

Metacounter

// v2
SendBird.queryChannelMetaCounter(CHANNEL_URL).increase(KEY, AMOUNT, ChannelMetaCounterQueryResult handler);
SendBird.queryChannelMetaCounter(CHANNEL_URL).get(KEYS, ChannelMetaCounterQueryResult handler);

// v3
channel.increaseMetaCounters(COUNTER_MAP, MetaCounterHandler handler);
channel.getMetaCounters(KEYS, MetaCounterHandler handler);

Event Handler

SendBirdEventHandler, SendBirdSystemEventHandler and SendBirdNotificationHandler are replaced by ChannelHandler. Please refer to Event Handler for details.


Push Notifications

From v3, you have to call registerPushTokenForCurrentUser explicitly after connection is made to register push tokens. Please refer to Push Notifications for details.

// v2
SendBird.login(SendBird.LoginOption.build(UUID).setUserName(NICKNAME).setGCMRegToken(TOKEN));

// v3
SendBird.connect(USER_ID, new SendBird.ConnectHandler() {
    @Override
    public void onConnected(User user, SendBirdException e) {
        SendBird.registerPushTokenForCurrentUser(TOKEN, RegisterPushTokenWithStatusHandler handler);
    }
});

Change Log

If you click the link below, you can see a list of significant features and fixes added with each release of SendBird Android SDK.

View the change log history