Home
/
Chat
/
Android

Open channel

An open channel is a Twitch-style public chat where users can easily join without permission. Sendbird Chat SDK now supports two operation systems for open channels, which are classic and dynamic partitioning. These two systems offer the same features and functions, except that dynamic partitioning allows open channels to accommodate a massive number of users.

Open channels can be used in short-lived live events, such as streaming, news-feed type messaging to massive audience, or events that don't require a permanent membership.

Note: To learn about differences between open channels and group channels, see Channel types.


Classic vs. Dynamic partitioning

Classic open channels are the original open channels Sendbird has been providing, and a single classic open channel can handle up to 1,000 participants.

Note: Sendbird applications created before December 15, 2020, are using classic open channels.

On the other hand, dynamic partitioning open channels are designed to accommodate an even larger number of users using a set number of subchannels, starting from 2,000 to 60,000 participants. This new system, called dynamic partitioning, enables flexible scaling of open channels by creating or merging subchannels within the open channels and evenly allocating participants among the subchannels while providing a seamless and well-paced chat experience to all users.

Note: The classic open channels will be deprecated by the end of March 2021 but the classic channels created before the deprecation will remain and function the same way. Meanwhile, all Chat SDK users will be automatically migrated to the new dynamic partitioning system when the deprecation takes place. If you wish to convert to dynamic partitioning open channels beforehand, contact our support team.

Learn more about how dynamic partitioning open channel operates in the Open channel guide of Platform API.


Create a channel

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

  1. In your dashboard, go to the Chat > Open channels, and then click Create channel at the top-right corner.
  2. In the dialog box that appears, specify the name, unique URL, cover image, and custom type of a channel.

You can also create a channel on demand or dynamically through the Chat SDK or the Chat API.

Light Color Skin
Copy
OpenChannel.createChannel(new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // An open channel is successfully created.
        // Through the "openChannel" parameter of the onResult() callback method,
        // you can get the open channel's data from the result object that Sendbird server has passed to the callback method.
        String channelUrl = openChannel.getUrl();
        ...
    }
});

Otherwise, you can create an open channel by passing a configured OpenChannelParams object as an argument to the parameter in the createChannel() method like the following.

Light Color Skin
Copy
List<String> operators = new ArrayList<>();
operators.add("Jeff");

OpenChannelParams params = new OpenChannelParams()
        .setName(NAME)
        .setChannelUrl(UNIQUE_CHANNEL_URL)  // For an open channel, you can create a channel by specifying its unique channel URL in an OpenChannelParams object.
        .setCoverImage(FILE)            // Or .setCoverUrl(COVER_URL)
        .setData(DATA)
        .setCustomType(CUSTOM_TYPE)
        .setOperatorUserIds(operators);  // Or .setOperators(List<User> operators)

OpenChannel.createChannel(params, new OpenChannel.OpenChannelCreateHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // An open channel with detailed configuration is successfully created.
        // By using openChannel.getUrl(), openChannel.getData(), openChannel.getCustomType(), and so on,
        // you can access the result object from Sendbird server to check your OpenChannelParams configuration.
        String channelUrl = openChannel.getUrl();
        ...
    }
});

When creating a channel, you can also append additional information like cover image and description by passing several arguments to the corresponding parameters.

Light Color Skin
Copy
OpenChannel.createChannel(NAME, COVER_IMAGE_OR_URL, DATA, OPERATOR_USERS, CUSTOM_TYPE, HANDLER);

List of arguments

ArgumentTypeDescription

NAME

string

Specifies the channel topic, or the name of the channel.

COVER_IMAGE_OR_URL

object

Specifies the cover image URL of the channel, or uploads a file for the cover image.

DATA

string

Specifies additional channel information such as a long description of the channel or JSON formatted string.

OPERATOR_USERS

list

Specifies a list of one or more users to register as operators of the channel. Operators can delete any messages, and also view all messages in the channel without any filtering or throttling.

CUSTOM_TYPE

string

Specifies the custom channel type which is used for channel grouping.

HANDLER

interface

Specifies the OpenChannelCreateHandler interface which contains the onResult() callback method to receive the response from Sendbird server for a channel creation request.

Using the getCoverUrl() and updateChannel() methods, you can get and update the cover image URL of a channel.

Note: You can also create a open channel using the Chat API which helps you control channel creations.


Enter a channel

A user must enter an open channel to receive messages. The user can enter up to 10 open channels at once, which are valid only within a current connection. So when a user is disconnected from Sendbird server with the disconnect() and reconnected to the server with the connect(), you should make sure the user re-enters the open channels for them to continue receiving messages.

When a user who is already a participant in an open channel moves the app to the background, the user will be disconnected from Sendbird server. But when the user's app returns to the foreground, the Chat SDK will automatically re-enter the user to the participating channel.

Note: When a user is reconnected by attempts of the SendBird instance from a temporary unstable connection, the Chat SDK will automatically re-enter the user to the participating channel.

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // Call the instance method of the result object in the "openChannel" parameter of the onResult() callback method.
        openChannel.enter(new OpenChannel.OpenChannelEnterHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {
                    // Handle error.
                }

                // The current user successfully enters the open channel,
                // and can chat with other users in the channel by using APIs.
                ...
            }
        });
    }
})l

Exit a channel

If a user exits an open channel, the user can't receive any messages from that channel.

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // Call the instance method of the result object in the "openChannel" parameter of the onResult() callback method.
        openChannel.exit(new OpenChannel.OpenChannelExitHandler() {
            @Override
            public void onResult(SendBirdException e) {
                if (e != null) {
                    // Handle error.
                }

                // The current user successfully exits the open channel.
                ...
            }
        });
    }
});

Freeze and unfreeze a channel

An open channel can be freezed only with the Sendbird Dashboard or Chat API as opposed to a group channel which operators of the channel can do that via the Chat SDK.

To freeze, go to your dashboard and do the following: on the Chat > Open channels, select an open channel to freeze, and click the Freeze icon at the upper right corner. To unfreeze, click the icon again with the frozen channel selected.

Note: In a frozen channel, participants can't chat with each other but the operators can send a message to the channel.


Delete a channel

Only the operators of an open channel can delete the channel. Otherwise, an error is returned through the OpenChannelDeleteHandler.

Note: The following code works properly in the operators' client apps only.

Light Color Skin
Copy
openChannel.delete(new OpenChannelDeleteHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The channel is successfully deleted.
        ...
    }
});

Retrieve a list of channels

You can retrieve a list of OpenChannel objects using the next() method of an OpenChannelListQuery instance like the following.

Light Color Skin
Copy
OpenChannelListQuery listQuery = OpenChannel.createOpenChannelListQuery();

listQuery.next(new OpenChannelListQuery.OpenChannelListQueryResultHandler() {
    @Override
    public void onResult(List<OpenChannel> openChannels, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of open channels is successfully retrieved.
        // Through the "openChannels" parameter of the onResult() callback method,
        // you can access the data of each open channel from the result list that Sendbird server has passed to the callback method.
        List<OpenChannel> channels = openChannels;
        ...
    }
});

Retrieve a channel by URL

Since a channel URL is a unique identifier of an open channel, you can use a URL when retrieving a channel object.

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // Through the "openChannel" parameter of the onResult() callback method,
        // the open channel object identified with the CHANNEL_URL is returned by Sendbird server,
        // and you can get the open channel's data from the result object.
        String channelName = openChannel.getName();
        ...
    }
});

Note: We recommend that you store a user's channel URLs to handle the lifecycle or state changes of your app, or any other unexpected situations. For example, when a user is disconnected from Sendbird server due to switching to another app temporarily, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance.


Send a message

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

Message typeDescription

UserMessage

A text message sent by a user

FileMessage

A binary file message sent by a user

In addition to these message types, you can further subclassify a message by specifying its custom type. This custom type takes on the form of a String and can be used to search or filter messages. It allows you to append information to your message and customize message categorization.

The following code shows several types of parameters that you can configure to customize text messages by using UserMessageParams. Under the UserMessageParams object, you can assign specific values to message, data and other properties. By assigning arbitrary string to the data property, you can set custom font size, font type or JSON object. To send your messages, you need to pass the UserMessageParams object as an argument to the parameter in the sendUserMessage() method.

Through the onSent() callback method of the sendUserMessage() method, Sendbird server always notifies whether your message has been successfully sent to the channel. When there is a delivery failure due to network issues, an exception is returned through the callback method.

Light Color Skin
Copy
List<String> userIDsToMention = new ArrayList<>();
userIDsToMention.add("Jeff");
userIDsToMention.add("Julia");

List<String> translationTargetLanguages = new ArrayList<>();
translationTargetLanguages.add("fr");       // French
translationTargetLanguages.add("de");       // German

UserMessageParams params = new UserMessageParams()
        .setMessage(TEXT_MESSAGE)
        .setCustomType(CUSTOM_TYPE)
        .setData(DATA)
        .setMentionType(MentionType.USERS)      // Either USERS or CHANNEL
        .setMentionedUserIds(userIDsToMention)      // Or .setMentionedUsers(LIST_OF_USERS_TO_MENTION)
        .setMetaArrays(Arrays.asList(new MessageMetaArray("itemType", Arrays.asList("tablet")), new MessageMetaArray("quality", Arrays.asList("best", "good")))
        .setTranslationTargetLanguages(translationTargetLanguages)
        .setPushNotificationDeliveryOption(PushNotificationDeliveryOption.DEFAULT); // Either DEFAULT or SUPPRESS

openChannel.sendUserMessage(params, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A text message with detailed configuration is successfully sent to the channel.
        // By using userMessage.getMessageId(), userMessage.getMessage(), userMessage.getCustomType(), and so on,
        // you can access the result object from Sendbird server to check your UserMessageParams configuration.
        // The current user can receive messages from other users through the onMessageReceived() method of an event handler.
        long messageId = userMessage.getMessageId();
        ...
    }
});

A user can also send binary files through the Chat SDK. The two ways to send a binary file are: sending the file itself, or sending a URL.

Sending a raw file means you're uploading it to Sendbird server where it can be downloaded in client apps. When you upload a file directly to the server, there is a size limit imposed on the file depending on your plan. You can see the limit in your dashboard and adjust it with our sales team.

The other option is to send a file hosted on your server. You can pass the file's URL, which represents its location, as an argument to a parameter. In this case, your file is not hosted on Sendbird server and it can only be downloaded from your own server. When you send a file message with a URL, there is no limit on the file size since it's not directly uploaded to Sendbird server.

Note: You can use sendFileMessages(), which is another method that allows you to send up to 20 file messages per one method call. Refer to our API Reference to learn more about it.

The following code shows several types of parameters that you can configure to customize file messages by using FileMessageParams. Under the FileMessageParams object, you can assign specific values to customType and other properties. To send your messages, you need to pass the FileMessageParams object as an argument to the parameter in the sendFileMessage() method.

Through the onSent() callback method of the sendFileMessage() method, Sendbird server always notifies whether your message has been successfully sent to the channel. When there is a delivery failure due to network issues, an exception is returned through the callback method.

Light Color Skin
Copy
// Sending a file message with a raw file
List<FileMessage.ThumbnailSize> thumbnailSizes = new ArrayList<>(); // Allowed number of thumbnail images: 3
thumbnailSizes.add(new ThumbnailSize(100,100));
thumbnailSizes.add(new ThumbnailSize(200,200));

List<String> userIDsToMention = new ArrayList<>();
userIDsToMention.add("Jeff");
userIDsToMention.add("Julia");

FileMessageParams params = new FileMessageParams()
        .setFile(FILE)              // Or .setFileURL(FILE_URL). You can also send a file message with a file URL.
        .setFileName(FILE_NAME)
        .setFileSize(FILE_SIZE)
        .setMimeType(MIME_TYPE)
        .setThumbnailSizes(thumbnailSizes)
        .setCustomType(CUSTOM_TYPE)
        .setMentionedType(MentionType.USERS)        // Either USERS or CHANNEL
        .setMentionedUserIds(userIDsToMention)      // Or .setMentionedUsers(LIST_OF_USERS_TO_MENTION)
        .setPushNotificationDeliveryOption(PushNotificationDeliveryOption.DEFAULT);     // Either DEFAULT or SUPPRESS

openChannel.sendFileMessage(params, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A file message with detailed configuration is successfully sent to the channel.
        // By using fileMessage.getMessageId(), fileMessage.getFileName(), fileMessage.getCustomType(), and so on,
        // you can access the result object from Sendbird server to check your FileMessageParams configuration.
        // The current user can receive messages from other users through the onMessageReceived() method of an event handler.
        long messageId = fileMessage.getMessageId();
        ...
    }
});

Send a critical alert message to iOS devices

A critical alert is a notification that can be sent to iOS devices even when mute or Do Not Disturb is turned on. Critical alert messages can be sent to iOS devices through the sendUserMessage() and sendFileMessage() methods. To do so, create an AppleCriticalAlertOptions instance and set it as an attribute of a UserMessageParams instance. Then pass the created UserMessageParams instance as an argument to a parameter in the sendUserMessage() or sendFileMessage() method.

Note: To learn more about how to set critical alerts, visit Apple critical alerts.

UserMessage
FileMessage
Light Color Skin
Copy
// Send a critical alert user message.
final UserMessageParams userMessageParams = new UserMessageParams();
final AppleCriticalAlertOptions options = new AppleCriticalAlertOptions("name", 0.7); // Acceptable values for `volume` range from 0 to 1.0, inclusive.
userMessageParams.setAppleCriticalAlertOptions(options);

openChannel.sendUserMessage(userMessageParams, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage message, SendBirdException e) {
        // Handle error.
    }
});
Light Color Skin
Copy
// Send a critical alert file message.
final FileMessageParams fileMessageParams = new FileMessageParams();
final AppleCriticalAlertOptions options = new AppleCriticalAlertOptions("name", 0.7); // Acceptable values for `volume` range from 0 to 1.0, inclusive.
fileMessageParams.setAppleCriticalAlertOptions(options);

openChannel.sendFileMessage(fileMessageParams, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage message, SendBirdException e) {
        // Handle error.
    }
});

Receive messages through a channel event handler

Messages sent from other participants can be received through the onMessageReceived() method in the channel event handler. A BaseMessage object for each received message is one of the following three message types.

Message typeDescription

UserMessage

A text message sent by a user

FileMessage

A binary file message sent by a user

AdminMessage

A text message sent by an admin through the Chat API

The UNIQUE_HANDLER_ID is a unique identifier to register multiple concurrent handlers.

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel channel, BaseMessage message) {
        // You can customize how to display the different types of messages with the result object in the "message" parameter.
        if (message instanceof UserMessage) {
            ...
        } else if (message instanceof FileMessage) {
            ...
        } else if (message instanceof AdminMessage) {
            ...
        }
    }
});

Reply to a message

Users can reply to a specific message in a channel through either the sendUserMessage() or sendFileMessage() method.

Depending on the type of the message a user intends to reply with, create a UserMessageParams or a FileMessageParams object and then specify the parentMessageId property of the object. Sending reply messages works the same way as sending regular messages to a channel, except replies have an additional parentMessageId property.

Reply with a text message

When replying to a message through the sendUserMessage() method, specify and pass a UserMessageParams object as an argument to a parameter in the method.

Light Color Skin
Copy
// Create a `UserMessageParams` object.
UserMessageParams params = new UserMessageParams();
params.setParentMessageId(PARENT_MESSAGE_ID);
...

// Pass the params to the parameter of the `sendUserMessage()` method.
openChannel.sendUserMessage(params, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A reply to a specific message in the form of a text message is successfully sent.
        ...
    }
});

List of arguments

ArgumentTypeDescription

PARENT_MESSAGE_ID

long

Specifies the unique ID of a parent message. A parent message is a message that has a thread of replies. If the message sent through the sendUserMessage() method is a parent message, the value of this property is 0. If the message is a reply to a parent message, the value is the message ID of the parent message.

Reply with a file message

When replying with a file message through the sendFileMessage() method, specify and pass a FileMessageParams object as an argument to a parameter in the method.

Light Color Skin
Copy
// Create a `FileMessageParams` object.
FileMessageParams params = new FileMessageParams();
params.setParentMessageId(PARENT_MESSAGE_ID);
...

// Pass the params to the parameter in the `sendFileMessage()` method.
openChannel.sendFileMessage(params, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A reply to a specific message in the form of a file message is successfully sent.
        ...
    }
});

List of arguments

ArgumentTypeDescription

PARENT_MESSAGE_ID

long

Specifies the unique ID of a parent message. A parent message is a message that has a thread of replies. If the message sent through the sendFileMessage() method is a parent message, the value of this property is 0. If the message is a reply to a parent message, the value is the message ID of the parent message.


Mention other participants in a message

When a participant wants to call the attention of other participants in an open channel where push notifications are not allowed by default, they can mention those participants in a message. To do so, you should:

  1. Specify a list of the user IDs to mention.
  2. Add the list to either UserMessageParams or FileMessageParams which may contain options for further action.
  3. Pass the params to either sendUserMessage() or sendFileMessage().
  4. Then only up to 10 participants mentioned in the message will be notified.
Light Color Skin
Copy
List<String> userIDsToMention = new ArrayList<>();
userIDsToMention.add("Harry");
userIDsToMention.add("Jay");
userIDsToMention.add("Jin");

UserMessageParams params = new UserMessageParams(MESSAGE)
    .setMentionedUserIds(userIDsToMention);

openChannel.sendUserMessage(params, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

Load previous messages

Using the load() method of a PreviousMessageListQuery instance which returns a list of BaseMessage objects, you can retrieve a set number of previous messages in an open channel. With a returned list, you can display the past messages in your UI once they have loaded.

Light Color Skin
Copy
// There should only be one single instance per channel view.
PreviousMessageListQuery listQuery = openChannel.createPreviousMessageListQuery();
listQuery.setCustomTypeFilter(CUSTOM_TYPE);
...

// Retrieving previous messages.
listQuery.load(LIMIT, REVERSE, new PreviousMessageListQuery.MessageListQueryResult() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

List of arguments

ArgumentTypeDescription

LIMIT

int

Specifies the number of results to return per call. Acceptable values are 1 to 100, inclusive. The recommended value for this parameter is 30.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If true, returns a list of messages which the latest comes at first and the earliest at last. the results are sorted in reverse order. If false, returns a list of messages which the earliest comes at first and the latest at last.

A limit parameter determines how many messages should be included in a returned list. A PreviousMessageListQuery instance itself does pagination of a result set based on the value of the limit parameter, and internally manages a token to retrieve the next page in the result set.

Each time the load() method is called, the instance retrieves a set number of messages in the next page and then updates the value of the token to complete the current call and prepare a next call.

If you create a new PreviousMessageListQuery instance and call the load() method, a set number of the most recent messages are retrieved because its token has nothing to do with the previously created instance. So we recommend that you create a single query instance and store it as a member variable for traversing through the entire message history.

Note: Before calling the load() method again, you must receive a success callback through the onResult() first.


Load messages by timestamp or message ID

You can retrieve a set number of previous and next messages on both sides of a specific timestamp in an open channel. You can do the same using a message ID as well.

By timestamp

Use the getMessagesByTimestamp() method to retrieve a set number of previous and next messages on both sides of a specific timestamp.

The following code shows several types of parameters that you can configure to customize a message query by using MessageListParams. Under the MessageListParams object, you can assign values to previousResultSize, messageType, customType, and other properties. To retrieve messages in a channel, you need to pass the MessageListParams object as an argument to the parameter in the getMessagesByTimestamp() method.

Light Color Skin
Copy
MessageListParams params = new MessageListParams();
params.setInclusive(IS_INCLUSIVE);
params.setPreviousResultSize(PREVIOUS_RESULT_SIZE);
params.setNextResultSize(NEXT_RESULT_SIZE);
params.setReverse(REVERSE);
params.setMessageType(MESSAGE_TYPE);
params.setCustomType(CUSTOM_TYPE);
...

openChannel.getMessagesByTimestamp(TIMESTAMP, params, new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of previous and next messages on both sides of a specified timestamp is successfully retrieved.
        // Through the "messages" parameter of the onResult() callback method,
        // you can access and display the data of each message from the result list that Sendbird server has passed to the callback method.
        List<BaseMessage> messages = messages;
        ...
    }
});

List of arguments

ArgumentTypeDescription

TIMESTAMP

long

Specifies the timestamp to be the reference point of a retrieval, in Unix milliseconds.

IS_INCLUSIVE

boolean

Determines whether to include the messages sent exactly on the TIMESTAMP.

PREV_RESULT_SIZE

int

Specifies the number of messages to retrieve, which are sent previously before a specified timestamp. 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.

NEXT_RESULT_SIZE

int

Specifies the number of messages to retrieve, which are sent later after a specified timestamp. 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 latest message.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

MESSAGE_TYPE

enum

Specifies the message type to filter the messages with the corresponding type. Acceptable values are MessageTypeFilter.ALL, MessageTypeFilter.USER, MessageTypeFilter.FILE, and MessageTypeFilter.ADMIN.

CUSTOM_TYPE

string

Specifies the custom message type to filter the messages with the corresponding custom type.

By message ID

You can also retrieve a set number of previous and next messages on both sides of a specific message ID in an open channel, using the getMessagesByMessageId() method and MessageListParams object.

Light Color Skin
Copy
MessageListParams params = new MessageListParams();
params.setInclusive(IS_INCLUSIVE);
params.setPreviousResultSize(PREVIOUS_RESULT_SIZE);
params.setNextResultSize(NEXT_RESULT_SIZE);
params.setReverse(REVERSE);
params.setMessageType(MESSAGE_TYPE);
params.setCustomType(CUSTOM_TYPE);
...

openChannel.getMessagesByMessageId(MESSAGE_ID, params, new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of previous and next messages on both sides of a specified message ID is successfully retrieved.
        // Through the "messages" parameter of the onResult() callback method,
        // you can access and display the data of each message from the result list that Sendbird server has passed to the callback method.
        List<BaseMessage> messages = messages;
        ...
    }
});

List of arguments

ArgumentTypeDescription

MESSAGE_ID

long

Specifies the unique ID of the message to be the reference point of a retrieval.

IS_INCLUSIVE

boolean

Determines whether to include the message identified with a specified message ID.

PREV_RESULT_SIZE

int

Specifies the number of messages to retrieve, which are sent previously before a specified message ID.

NEXT_RESULT_SIZE

int

Specifies the number of messages to retrieve, which are sent later after a specified timestamp.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

MESSAGE_TYPE

enum

Specifies the message type to filter the messages with the corresponding type. Acceptable values are MessageTypeFilter.ALL, MessageTypeFilter.USER, MessageTypeFilter.FILE, and MessageTypeFilter.ADMIN.

CUSTOM_TYPE

string

Specifies the custom message type to filter the messages with the corresponding custom type.


List messages along with their replies by timestamp or message ID

You can retrieve messages and their replies in a specific thread through one of the load(), getMessagesByTimestamp(), or getMessagesByMessageId() methods.

First, messages in an open channel must be retrieved. The load() method of a PreviousMessageListQuery instance returns a list of BaseMessage objects. By using this method, you can retrieve previous messages in a specific channel.

To include the replies of the target messages in the results, change the value to true by using the setIncludeReplies() method.

Light Color Skin
Copy
PreviousMessageListQuery listQuery = openChannel.createPreviousMessageListQuery();
listQuery.setLimit(LIMIT);
listQuery.setReverse(REVERSE);
listQuery.setIncludeReplies(INCLUDE_REPLIES);
listQuery.setIncludeThreadInfo(INCLUDE_THREAD_INFO);
listQuery.setIncludeParentMessageText(INCLUDE_PARENT_MESSAGE_TEXT);
...

// This retrieves previous messages in a channel.
listQuery.load(new PreviousMessageListQuery.MessageListQueryResult() {
    @Override
    public void onResult(List<BaseMessage> list, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

List of arguments

ArgumentTypeDescription

LIMIT

int

Specifies the number of results to return per call. Acceptable values are 1 to 100, inclusive. The recommended value for this parameter is 30.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

INCLUDE_REPLIES

boolean

Determines whether to include replies in the results.

INCLUDE_THREAD_INFO

boolean

Determines whether to include the thread information of the messages in the results when the results contain parent messages.

INCLUDE_PARENT_MESSAGE_TEXT

boolean

Determines whether to include the parent message text in the results when the retrieved messages are replies in a thread. If the type of the parent message is UserMessage, the value is a message property. If it is FileMessage, the value is the name of the uploaded file.

By timestamp

The getMessagesByTimestamp() method of a BaseChannel instance retrieves a list of BaseMessage objects.

When using the method above, you can also pass a MessageListParams object as an argument to the parameter in the getMessagesByTimestamp() method.

Light Color Skin
Copy
MessageListParams params = new MessageListParams();
params.setPreviousResultSize(PREV_RESULT_SIZE);
params.setNextResultSize(NEXT_RESULT_SIZE);
params.setInclusive(INCLUSIVE);
params.setReverse(REVERSE);
params.setIncludeReplies(INCLUDE_REPLIES);
params.setIncludeThreadInfo(INCLUDE_THREAD_INFO);
params.setIncludeParentMessageText(INCLUDE_PARENT_MESSAGE_TEXT);
...

openChannel.getMessagesByTimestamp(TIMESTAMP, params, new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of previous and next messages on both sides of a specified timestamp is successfully retrieved.
        // Through the "messages" parameter of the onResult() callback method,
        // you can access and display the data of each message from the result list that Sendbird server has passed to the callback method.
        List<BaseMessage> messages = messages;
        ...
    }
});

List of arguments

ArgumentTypeDescription

TIMESTAMP

long

Specifies the timestamp to be the reference point for messages to retrieve, in Unix milliseconds format. Messages sent before or after the timestamp can be retrieved.

PREV_RESULT_SIZE

int

Specifies the number of messages to retrieve that were sent before the specified timestamp or message ID.

NEXT_RESULT_SIZE

int

Specifies the number of messages to retrieve that were sent after the specified timestamp or message ID.

INCLUSIVE

boolean

Determines whether to include the messages with the matching timestamp or message ID in the results.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

INCLUDE_REPLIES

boolean

Determines whether to include replies in the results.

INCLUDE_THREAD_INFO

boolean

Determines whether to include the thread information of the messages in the results when the results contain parent messages.

INCLUDE_PARENT_MESSAGE_TEXT

boolean

Determines whether to include the parent message text in the results when the retrieved messages are replies in a thread. If the type of the parent message is UserMessage, the value is a message property. If it is FileMessage, the value is the name of the uploaded file.

By message ID

The getMessagesByMessageId() method of a BaseChannel instance retrieves a set number of previous and next messages on both sides of a specific message ID in a channel.

Light Color Skin
Copy
openChannel.getMessagesByMessageId(MESSAGE_ID, params, new BaseChannel.GetMessagesHandler() {
    @Override
    public void onResult(List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of previous and next messages on both sides of a specified message ID is successfully retrieved.
        // Through the "messages" parameter of the onResult() callback method,
        // you can access and display the data of each message from the result list that Sendbird server has passed to the callback method.
        List<BaseMessage> messages = messages;
        ...
    }
});

List of arguments

ArgumentTypeDescription

MESSAGE_ID

long

Specifies the message ID to be the reference point for messages to retrieve. Messages sent before or after the message with the matching message ID can be retrieved.


List replies of a parent message

With the timestamp of the parent message, you can retrieve a single message with its replies by passing a TreadMessageListParams object as an argument to the parameter in the getThreadedMessagesByTimestamp() method.

Light Color Skin
Copy
// Create a `ThreadMessageListParams` object.
ThreadMessageListParams params = new ThreadMessageListParams();
params.setPreviousResultSize(PREV_RESULT_SIZE);
params.setNextResultSize(NEXT_RESULT_SIZE);
params.setInclusive(INCLUSIVE);
params.setReverse(REVERSE);
params.setIncludeParentMessageText(INCLUDE_PARENT_MESSAGE_TEXT);
...

// Pass the params as an argument to the parameter in the `getThreadedMessagesByTimestamp()` method.
parentMessage.getThreadedMessagesByTimestamp(TIMESTAMP, params, new BaseMessage.GetThreadedMessagesHandler() {
    @Override
    public void onResult(BaseMessage parentMessage, List<BaseMessage> messages, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // A list of replies of the specified parent message timestamp is successfully retrieved.
        ...
    }
});

List of arguments

ArgumentTypeDescription

TIMESTAMP

long

Specifies the timestamp to be the reference point of the retrieval, in Unix milliseconds format.

PREV_RESULT_SIZE

int

Specifies the number of messages to retrieve that were sent before the specified timestamp.

NEXT_RESULT_SIZE

int

Specifies the number of messages to retrieve that were sent after the specified timestamp.

INCLUSIVE

boolean

Determines whether to include the messages with the matching timestamp in the results.

REVERSE

boolean

Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

INCLUDE_PARENT_MESSAGE_TEXT

boolean

Determines whether to include the parent message text in the results when the messages are replies in a thread. If the type of the parent message is UserMessage, the value is a message property. If it is FileMessage, the value is the name of the uploaded file.


Retrieve a message

You can retrieve a specific message by creating and passing the MessageRetrievalParams object to the getMessage() method as a parameter.

Light Color Skin
Copy
// Create a `MessageRetrievalParams` object.
MessageRetrievalParams params = new MessageRetrievalParams(CHANNEL_URL, CHANNEL_TYPE, MESSAGE_ID);
...

// Pass the params as an argument to the parameter in the `getMessage()` method.
BaseMessage.getMessage(params, new BaseMessage.GetMessageHandler() {
    @Override
    public void onResult(BaseMessage message, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The specified message is successfully retrieved.
        ...
    }
});

List of arguments

ArgumentTypeDescription

CHANNEL_URL

String

Specifies the URL of the channel to retrieve the message.

CHANNEL_TYPE

BaseChannel.ChannelType

Specifies the type of the channel.

MESSAGE_ID

long

Specifies the unique ID of the message to retrieve.


Update a message

A user can update any of their own text and file messages sent. An error is returned if a user attempts to update another user's messages. In addition, channel operators can update any messages sent in the channel.

User message
File message
Light Color Skin
Copy
UserMessageParams params = new UserMessageParams()
        .setMessage(NEW_TEXT_MESSAGE)
        .setCustomType(NEW_CUSTOM_TYPE)
        .setData(NEW_DATA);

// The MESSAGE_ID below indicates the unique message ID of a UserMessage object to update.
openChannel.updateUserMessage(MESSAGE_ID, params, new BaseChannel.UpdateUserMessageHandler() {
    @Override
    public void onUpdated(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The message is successfully updated.
        // Through the "userMessage" parameter of the onUpdated() callback method,
        // you could check if the update operation has been performed correctly.
        String text = userMessage.getMessage();
        ...
    }
});
Light Color Skin
Copy
FileMessageParams params = new FileMessageParams()
        .setFileURL(NEW_FILE_URL)       // The file in a message can't be updated.
        .setFileName(NEW_FILE_NAME)
        .setFileSize(NEW_FILE_SIZE)
        .setCustomType(NEW_CUSTOM_TYPE);

// The MESSAGE_ID below indicates the unique message ID of a FileMessage object to update.
openChannel.updateFileMessage(MESSAGE_ID, params, new BaseChannel.UpdateFileMessageHandler() {
    @Override
    public void onUpdated(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The message is successfully updated.
        // Through the "fileMessage" parameter of the onUpdated() callback method,
        // you could check if the update operation has been performed correctly.
        String customType = fileMessage.getCustomType();
        ...
    }
});

If a message is updated, the onMessageUpdated() method in the channel event handler will be invoked on all channel participants' devices except the one that updated the message.

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    ...

    @Override
    public void onMessageUpdated(BaseChannel channel, BaseMessage message) {
        ...
    }

    ...
});

Delete a message

A user can delete any messages sent by themselves. An error is returned if a user attempts to delete the messages of other participants. Also channel operators can delete any messages in the channel.

Light Color Skin
Copy
// The BASE_MESSAGE below indicates a BaseMessage object to delete.
openChannel.deleteMessage(BASE_MESSAGE, new BaseChannel.DeleteMessageHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The message is successfully deleted from the channel.
        ...
    }
});

If a message is deleted, the onMessageDeleted() method in the channel event handler will be invoked on all channel participants' devices including the one that deleted the message.

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    ...

    @Override
    public void onMessageDeleted(BaseChannel channel, long messageId) {
        ...
    }

    ...
});

Copy a message

A user can copy and send their own message in the same channel or to another channel.

User message
File message
Light Color Skin
Copy
openChannel.copyUserMessage(TARGET_CHANNEL, MESSAGE_TO_COPY, new BaseChannel.CopyUserMessageHandler() {
    @Override
    public void onCopied(UserMessage userMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The message is successfully copied to the target channel.
        ...
    }
});
Light Color Skin
Copy
openChannel.copyFileMessage(TARGET_CHANNEL, MESSAGE_TO_COPY, new BaseChannel.CopyFileMessageHandler() {
    @Override
    public void onCopied(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The message is successfully copied to the target channel.
        ...
    }
});

List of arguments

ArgumentTypeDescription

TARGET_CHANNEL

object

Specifies a target channel to send a copied message to.

MESSAGE_TO_COPY

object

Specifies a message to copy.

HANDLER

interface

Specifies the handler interface which contains the onCopied() callback method to receive the response from Sendbird server for a message copy request.


Retrieve a list of participants

You can retrieve a list of participants who are currently online and receiving all messages from an open channel.

Light Color Skin
Copy
ParticipantListQuery listQuery = openChannel.createParticipantListQuery();

listQuery.next(new UserListQuery.UserListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

Retrieve the latest information on participants

To retrieve the latest and updated information on each online participant in an open channel, you need another ParticipantListQuery instance for the channel. Like the Retrieve a list of participants section above, create a query instance using the channel.createParticipantListQuery(), and then call its next() method consecutively to retrieve the latest.

You can also retrieve the latest and updated information on users at the application level. Like the Retrieve a list of users section, create a new ApplicationUserListQuery instance using the SendBird.createApplicationUserListQuery(), and then call its next() method consecutively to retrieve the latest.

When retrieving the online (connection) status of a user, by calling the user.getConnectionStatus() at each User object in a returned list, you can get the user's current connection status. The getConnectionStatus() returns one of the following two values:

getConnectionStatus()

ValueDescription

User.ConnectionStatus.OFFLINE

The user is not connected to Sendbird server.

User.ConnectionStatus.ONLINE

The user is connected to Sendbird server.

Note: If you need to keep track of the connection status of some users in real time, we recommend that you call periodically the next() method of an ApplicationUserListQuery instance with its userIdsFilter filter specified, perhaps in intervals of one minute or more.


Retrieve a list of operators

You can follow the simple implementation below to retrieve a list of operators who monitor and control the activities in an open channel.

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // Retrieving a list of operators.
        for (User operator : openChannel.getOperators()) {
            ...
        }
    }
});

Register operators

You can register participants as operators of an open channel.

Light Color Skin
Copy
openChannel.addOperators(USER_IDS, new AddOperatorsHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The participants are successfully registered as operators of the channel.
        ...
    }
});

Cancel the registration of operators

You can cancel the registration of operators from an open channel but leave them as participants.

Light Color Skin
Copy
openChannel.removeOperators(USER_IDS, new RemoveOperatorsHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The cancel operation is succeeded,
        // and you could display some message to those who are not operators anymore.
        ...
    }
});

If you want to cancel the registration of all operators in a channel at once, use the following code.

Light Color Skin
Copy
openChannel.removeAllOperators(new RemoveAllOperatorsHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        // The cancel operation is succeeded,
        // and you could display some message to those who are not operators anymore.
        ...
    }
});

Retrieve a list of banned or muted users

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

Light Color Skin
Copy
// Retrieving banned users
BannedUserListQuery listQuery = openChannel.createBannedUserListQuery();

listQuery.next(new UserListQuery.UserListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

// Retrieving muted users
MutedUserListQuery listQuery = openChannel.createMutedUserListQuery();

listQuery.next(new UserListQuery.UserListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

Ban and unban a user

Operators of an open channel can remove any users that behave inappropriately in the channel by using our Ban feature. Banned users are immediately expelled from a channel and allowed to participate in the channel again after the time period set by the operators. Operators can ban and unban users from open channels using the following code.

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        if (openChannel.isOperator(SendBird.getCurrentUser())) {
            // Ban a user.
            openChannel.banUser(USER, SECONDS, new OpenChannel.OpenChannelBanHandler() {
                @Override
                public void onResult(SendBirdException e) {
                    if (e != null) {
                        // Handle error.
                    }

                    // The user is successfully banned from the channel.
                    // You could notify the user of being banned by displaying a prompt.
                    ...
                }
            });

            // Unban a user.
            openChannel.unbanUser(USER, new OpenChannel.OpenChannelUnbanHandler() {
                @Override
                public void onResult(SendBirdException e) {
                    if (e != null) {
                        // Handle error.
                    }

                    // The user is successfully unbanned for the channel.
                    // You could notify the user of being unbanned by displaying a prompt.
                    ...
                }
            });
        }
    }
});

Note: You can also use banUserWithUserId() and unbanUserWithUserID() methods, instead of banUser() and unbanUser() methods, as they have the same functionalities.


Mute and unmute a user

Operators of an open channel can prohibit the selected users from sending messages using our Mute feature. Muted users remain in the channel and are allowed to view the messages, but can't send any messages until the operators unmute them. Operators can mute and unmute users in open channels using the following code:

Light Color Skin
Copy
OpenChannel.getChannel(CHANNEL_URL, new OpenChannel.OpenChannelGetHandler() {
    @Override
    public void onResult(OpenChannel openChannel, SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        if (openChannel.isOperator(SendBird.getCurrentUser())) {
            // Mute a user.
            openChannel.muteUser(USER, new OpenChannel.OpenChannelMuteHandler() {
                @Override
                public void onResult(SendBirdException e) {
                    if (e != null) {
                        // Handle error.
                    }

                    // The user is successfully muted in the channel.
                    // You could notify the user of being muted by displaying a prompt.
                    ...
                }
            });

            // Unmute a user.
            openChannel.unmuteUser(USER, new OpenChannel.OpenChannelUnmuteHandler() {
                @Override
                public void onResult(SendBirdException e) {
                    if (e != null) {
                        // Handle error.
                    }

                    // The user is successfully unmuted in the channel.
                    // You could notify the user of being unmuted by displaying a prompt.
                    ...
                }
            });
        }
    }
});

Note: You can also use muteUserWithUserId() and unmuteUserWithUserID() methods, instead of muteUser() and unmuteUser() methods, as they have the same functionalities.


Report a message, a user, or a channel

In an open channel, a user can report suspicious or harassing messages as well as the other users who use abusive language. The user can also report channels if there are any inappropriate content or activity within the channel. Based on this feature and our report API, you can build your own in-app system for managing objectionable content and subject.

Light Color Skin
Copy
// Reporting a message.
openChannel.reportMessage(MESSAGE_TO_REPORT, REPORT_CATEGORY, DESCRIPTION, new BaseChannel.ReportMessageHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

// Reporting a user.
openChannel.reportUser(OFFENDING_USER, REPORT_CATEGORY, DESCRIPTION, new BaseChannel.ReportUserHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

// Reporting a channel.
openChannel.report(REPORT_CATEGORY, DESCRIPTION, new BaseChannel.ReportHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {
            // Handle error.
        }

        ...
    }
});

List of arguments

ArgumentTypeDescription

MESSAGE_TO_REPORT

object

Specifies the message to report for its suspicious, harassing, or inappropriate content.

OFFENDING_USER

object

Specifies the user who uses offensive or abusive language such as sending explicit messages or inappropriate comments.

REPORT_CATEGORY

enum

Specifies a report category which indicates the reason for reporting. Acceptable values are limited to ReportCategory.SUSPICIOUS, ReportCategory.HARASSING, ReportCategory.INAPPROPRIATE, and ReportCategory.SPAM.

DESCRIPTION

string

Specifies additional information to include in the report.