Android
Group Channel Advanced

Group Channel: Advanced

This page explains the advanced features for group channels. Some of them are the premium features available only to a paying user.


Add other users as friends

A user can easily search for other users, add them as friends, and chat with them. In order to add a friend, the user should first upload the other user’s unique key to Sendbird server, such as a phone number that is hashed for privacy. When the unique key is uploaded, the server will identify and match its corresponding user based on the key, and notify the results to the matched user. Then, the matched user can decide whether to add or ignore the friend request.

Note: Before using this feature, make sure the user information includes at least one at least one unique key. If not, update the user information to incorporate unique keys. We recommend that you include unique keys when creating a user.

Light Color Skin
Copy
// Uploading other users' unique keys to Sendbird server for discovering the corresponding users
Map<String, String> discoveryMap = new HashMap<>(); // Store names of friends by unique key 
discoveryMap.put("0001-0002-0003", "John");     // A pair of a unique key and a friend's name
discoveryMap.put("0004-0005-0006", "Jay");
discoveryMap.put("0007-0008-0009", "Jin");

SendBird.uploadFriendDiscoveries(discoveryMap, new SendBird.UploadFriendDiscoveriesHandler() {
    @Override
    public void onResult(SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

// Ignoring particular users when Sendbird server discovers the matched users  
List<String> discoveryKeys = new ArrayList<>();
discoveryKeys.add("0001-0002-0003");
discoveryKeys.add("0004-0005-0006");
discoveryKeys.add("0007-0008-0009");

SendBird.deleteFriendDiscoveries(discoveryKeys, new SendBird.DeleteFriendDiscoveriesHandler() {
    @Override
    public void onResult(SendBirdException e) { 
        if (e != null) {    // Error.
            return;
        }
    }
});

Through the onFriendsDiscovered() in the user event handler, the current user will receive a callback from the server which contains a list of users whose keys match with the ones uploaded. Based on the list, the user can add them as friends through the addFriends() method:

Light Color Skin
Copy
SendBird.addUserEventHandler(UNIQUE_HANDLER_ID, new SendBird.UserEventHandler() {
    @Override
    public void onFriendsDiscovered(List<User> users) {
        if(users != null) {
            List<String> friendIds = new ArrayList<>();
            // You can show users who match the uploaded unique keys on a list view.
            // Then the current user can decide to add them as friends or ignore them. 
            for (User user : users} { 
                friendIds.add(user.getUserId());    
            }

            // Adding new friends
            SendBird.addFriends(friendIds, new SendBird.AddFriendsHandler() {
                @Override
                public void onResult(List<User> list, SendBirdException e) {
                    if (e != null) {    // Error.
                        return;
                    }       
                }
            }
        }   
    }
});

The current user can also remove existing friends through the deleteFriends() method:

Light Color Skin
Copy
// Deleting existing friends
SendBird.deleteFriends(friendIds, new SendBird.DeleteFriendsHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) { 
        if (e != null) {    // Error.
            return;
        }       
    }
});

A list of friends of the current user can be retrieved through the FriendListQuery's next() method:

Light Color Skin
Copy
FriendListQuery friendListQuery = SendBird.createFriendListQuery();
friendListQuery.next(new FriendListQuery.FriendListQueryResultHandler() {
    @Override
    public void onResult(List<User> list, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

Send typing indicators to other members

If the startTyping() and endTyping() methods are called while the current user is typing a text message in a group channel, the onTypingStatusUpdated() in the channel event handler will be invoked on all channel members' devices except the one that belongs to the current user.

Light Color Skin
Copy
groupChannel.startTyping();
groupChannel.endTyping();
...

// To listen to an update from all the other channel members' client apps, implement the 'onTypingStatusUpdated()' with things to do when notified.
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 the channel.
        }
    }
});

Mark messages as delivered

To mark messages as delivered when a group channel member receives a push notification for the message from FCM, either the SendBird.markAsDelivered() static method or the groupChannel.markAsDelivered() instance method should be called.

Using a static method
Light Color Skin
Copy
public class FirebaseMessagingServiceEx extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        try {
            JSONObject sendBird = new JSONObject(remoteMessage.getData().get("sendbird"));
            JSONObject channel = (JSONObject) sendBird.get("channel");
            String channelUrl = (String) channel.get("channel_url");

            // Implement the following
            SendBird.markAsDelivered(channelUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
Using an instance method
Light Color Skin
Copy
public class FirebaseMessagingServiceEx extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        try {
            JSONObject sendBird = new JSONObject(remoteMessage.getData().get("sendbird"));
            JSONObject channel = (JSONObject) sendBird.get("channel");
            String channelUrl = (String) channel.get("channel_url");

            GroupChannel.getChannel(channelUrl, new GroupChannel.GroupChannelGetHandler() {
                @Override
                public void onResult(GroupChannel channel, SendBirdException e){
                    if (channel != null) {
                        // implement the following
                        channel.markAsDelivered();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void sendNotification(FirebaseMessagingServiceEx firebaseMessagingServiceEx, String message, String channelUrl) {
        // TODO: Send notifications here.
    }
}

When a message is delivered to an online group channel member, it is automatically marked as delivered and the other online members are notified of delivery receipt through the onDeliveryReceiptUpdated() method in the channel event handler. However, when it is delivered to an offline group channel member as a push notification, the message can be marked as delivered through the groupChannel.markAsDelivered(), and other online members are notified of the delivery receipt through the onDeliveryReceiptUpdated().

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
    }

    @Override
    public void onDeliveryReceiptUpdated(GroupChannel channel) {
        ... 

    }
});

Mark messages as read

To keep the most up-to-date and accurate read status of messages for all group channel members, the markAsRead() method should be called every time one of the members reads messages by entering the channel from a channel list or bringing the opened channel view to the foreground.

If the current user opens a channel and the markAsReadAll() is called, Sendbird server will update both the unread message count of the individual channel and the total unread message count of all the group channels joined by the user. The server then notifies the change of read status to all members' devices through the onReadReceiptUpdated() method in the channel event handler, except the one that is being used by the current user.

Note : When a channel member sends a message to the channel, Sendbird server updates the member's read receipt to the time when the message has sent. Meanwhile, the read receipts of other channel members can be updated when the markAsRead() method is called. If a new member joins the channel, the method works differently based on the value of the display_past_message property of your Sendbird application. If the property is set to true, the new member’s read receipt will be updated to the sent time of the last message in the channel. If false, it will be updated to 0.

Light Color Skin
Copy
// Call the 'markAsRead()' when the current user views unread messages in a group channel.
groupChannel.markAsRead();
...

// To listen to an update from all the other channel members' client apps, implement the 'onReadReceiptUpdated()' with things to do when notified.
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onReadReceiptUpdated(GroupChannel groupChannel) {
        if (currentGroupChannel.getUrl().equals(groupChannel.getUrl())) {
            // For example, code for redrawing a channel view.
        }
    }
});

Note: The display_past_message property determines whether to display past messages to newly joined members when they enter the channel. This property is also linked to the Chat history option, which can be adjusted in your dashboard under Settings > Chat > Messages.


Retrieve number of members who haven't received a message

You can retrieve the number of members who haven’t received a specific message in a group channel. If zero is returned, it means that the message has been delivered to all the other members.

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel baseChannel, BaseMessage baseMessage) {
    }
    ...

    @Override
    public void onDeliveryReceiptUpdated(GroupChannel channel) {
        Boolean isAllDelivered = channel.getUndeliveredMemberCount(MESSAGE) == 0;
        ...

    }
    ...

});

Retrieve members who have read a message

Using the getReadMembers() method, you can view members who have read a specific message in a group channel. The method returns a list of channel members who have read the message by comparing the message’s creation time and the channel members’ read receipt. The list will exclude the current user and the message sender.

Note: Read receipt indicates the timestamp of the latest time when each user has read messages in the channel, in Unix milliseconds.

If you want to keep track of who has read a new message, we recommend that you use the getReadMembers() in the onReadReceiptUpdated(). Then the client app will receive a callback from Sendbird server whenever a channel member reads a message. To do so, you should pass the new message object as an argument to a parameter in the getReadMembers() through the onReadReceiptUpdated().

Light Color Skin
Copy
List<User> readMembers = groupChannel.getReadMembers(MESSAGE);

Note: Using the getUnreadMembers() method, you can also view members who have not read a specific message in a group channel, except the current user and the message sender. In the meantime, you can get information on each channel member's read receipt through the getReadStatus() method.


Retrieve number of members who haven't read a message

Using the getReadReceipt() method, you can get the number of members who have not read a specific message in a group channel. To get the exact value, the channel should be updated first through the markAsRead() before calling the getReadReceipt().

Light Color Skin
Copy
// Call the 'markAsRead()' when the current user views unread messages in a group channel.
groupChannel.markAsRead();
...

// To listen to an update from all the other channel members' client apps, implement the 'onReadReceiptUpdated()' with things to do when notified.
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onReadReceiptUpdated(GroupChannel groupChannel) {
        if (currentGroupChannel.getUrl().equals(groupChannel.getUrl())) {
            ... 

            for (BaseMessage message : messages) {
                int unreadCount = groupChannel.getReadReceipt(message);
                if (unreadCount <= 0) { 
                    // All members have read the message.
                } else {
                    // Some of members haven't read the message yet.
                }
            }
        }
    }
});

Retrieve the last message of a channel

You can view the last message of a group channel.

Light Color Skin
Copy
BaseMessage lastMessage = groupChannel.getLastMessage();

Retrieve number of unread messages in a channel

You can retrieve the total number of the current user's unread messages in a group channel.

Light Color Skin
Copy
int unreadMessageCount = groupChannel.getUnreadMessageCount();

Retrieve number of unread messages in all channels

You can retrieve the total number of the current user's unread messages in all joined group channels.

Light Color Skin
Copy
SendBird.getTotalUnreadMessageCount(new GroupChannel.GroupChannelTotalUnreadMessageCountHandler() {
    @Override
    public void onResult(int totalUnreadMessageCount, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

Retrieve number of channels with unread messages

You can retrieve the total number of the current user's joined group channels with one or more unread messages.

Light Color Skin
Copy
SendBird.getTotalUnreadChannelCount(new GroupChannel.GroupChannelTotalUnreadChannelCountHandler() {
    @Override
    public void onResult(int totalUnreadChannelCount, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

Send an admin message

If you are using the Custom Plan, you can send admin messages to a group channel using Sendbird Dashboard or Chat Platform API. To send an admin message through your dashboard, go to the Chat > Group channels, select a group channel, find the message box below, click the Admin message tab, and then write your message in the box. An admin message is limited to 1,000 characters.

Unlike other types of messages, a push notification for an admin message is not available by default. If you want assistance on this, contact our sales team.

Note: For clients using the Free Plan, a suggesting message to upgrade to the Custom Plan will be returned when attempting to send an admin message using the Chat API.


Add extra data to a message

You have the option to create further actions in a channel by using extra data in a message. You can add one or more key-values items to a message which you can save, update, or remove, when necessary. Based on those items, you can design and implement several different actions such as measuring user engagement within a chosen time limit through polls or counting how many times a message has been copied by members.

Note: For the quality of performance, every Sendbird application has its own limits to how many key-values items you can add to a single message, as well as the maximum number of values an item can have. If you would like more information on these limits, contact our sales team.

Light Color Skin
Copy
// When a message has been successfully sent to a channel, create items with keys.
List<String> itemKeysToCreate = new ArrayList<>();
itemKeysToCreate.add("referees");
itemKeysToCreate.add("games");

groupChannel.createMessageMetaArrayKeys(BASE_MESSAGE, itemKeysToCreate, new BaseChannel.MessageMetaArrayHandler() {
    @Override
    public void onResult(BaseMessage baseMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

// Adding values to specific items by their keys.
List<String> people = new ArrayList<>();
people.add("John");
people.add("Brandon");
people.add("Harry");
people.add("Jay");

List<String> events = new ArrayList<>();
events.add("soccer");
events.add("baseball");
events.add("basketball");

Map<String, List<String>> valuesToAdd = new HashMap<>();
valuesToAdd.put("referees", people);
valuesToAdd.put("games", events);

groupChannel.addMessageMetaArrayValues(BASE_MESSAGE, valuesToAdd, new BaseChannel.MessageMetaArrayHandler() {
    @Override
    public void onResult(BaseMessage baseMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

// Removing existing values of specific items by their keys.
List<String> notAvailablePeople = new ArrayList<>();
notAvailablePeople.add("Brandon");
notAvailablePeople.add("Jay");

Map<String, List<String>> valuesToRemove = new HashMap<>();
valuesToRemove.put("referees", notAvailablePeople);

groupChannel.removeMessageMetaArrayValues(BASE_MESSAGE, valuesToRemove, new BaseChannel.MessageMetaArrayHandler() {
    @Override
    public void onResult(BaseMessage baseMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

// Deleting items by their keys.
List<String> itemKeysToDelete = new ArrayList<>();
itemKeysToDelete.add("referees");
itemKeysToDelete.add("games");

groupChannel.deleteMessageMetaArrayKeys(BASE_MESSAGE, itemKeysToDelete, new BaseChannel.MessageMetaArrayHandler() {
    @Override
    public void onResult(BaseMessage baseMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});

To get the key-values items of a message, use the message.getAllMetaArrays() method.


Display Open Graph tags in a message

The Chat SDK supports the URL link preview when a message text contains the URL of a web page.

Note: Starting in 2021, this feature will be turned on by default. For the time being, contact our support team to enable the featur

OGMetaData for Android

OGMetaData

OGMetaData is a class that holds the Open Graph (OG) protocol-related data, including the four properties: title, URL, description, and image of an OG object.

Note: Some websites don’t provide the OG metadata fields mentioned above. In that case, even though the Open Graph protocol states them as requirements, all of the four getter methods may return null.

MethodDescription

getTitle()

Returns the title of the OG object as it should appear within the graph. The value can be null.

getUrl()

Returns the canonical URL of the object that can be used as its permanent ID in the graph. The value can be null.

getDescription()

Returns the description of the object. The value can be null.

getOGImage()

Returns an OGImage object that contains information about the image that this Open Graph points to. The OGImage also holds its own properties such as type, URL, and size. However, the value can be null.

OGImage

OGImage is a class that holds image-related data for an OGMetaData object. The OGImage class can also have six optional structured properties of URL, secure URL, type, width, height, and alt.

Note: Except for width and height, other fields such as URL, secure URL, type, and alt can be null. Width and height are set to 0 if the target website doesn’t provide such data.

MethodDescription

getUrl()

Returns the URL of an image object within the Open Graph. The value can be null.

getSecureUrl()

Returns an alternative url to use if the webpage requires HTTPS. The value can be null.

getType()

Returns a media type or MIME type of this image. The value can be null.

getWidth()

Returns the number of pixels horizontal. When the value is unavailable, this method returns 0.

getHeight()

Returns the number of pixels vertical. When the value is unavailable, this method returns 0.

getAlt()

Returns a description of what is in the image, not a caption of the image. The alt attribute is designed to provide a fuller context of the OGImage object and help users better understand it when they can’t load or see the image. The value can be null.

How it works

If a user sends a message with a web page URL and the linked web page possesses Open Graph (OG) tags, or OG metadata, Sendbird server parses the message content, extracts the URL in the message, gets the OG metadata from it, and creates an OG metadata object for the message. Then message recipients will get the parsed message with its OG metadata object through the onMessageReceived() method in the channel event handler of the SDK. On the other hand, the message sender will do the same through the onMessageUpdated().

Displaying an OG metadata object is available for two subtypes of BaseMessage: UserMessage and AdminMessage. If the content of a BaseMessage object includes a web page URL containing OG metadata, the BaseMessage.getOgMetaData() method returns OGMetaData and OGImage objects.

If Sendbird server doesn’t have cache memory of the OG metadata of the given URL, the BaseMessage.getOgMetaData() method can return null due to the time it takes to fetch the OG metadata from the corresponding remote web page. In the meantime, the message text containing the URL will be delivered first to message recipients’ client app through the onMessageReceived() method. When the server completes fetching, the onMessageUpdated() method will be called and the message with its OG metadata object will be delivered to the recipients’ client app. However, if Sendbird server has already cached the OG metadata of the URL, the BaseMessage.getOgMetaData() method returns the message and its OGMetaData object instantly and the onMessageUpdated() method won’t be called.

Light Color Skin
Copy
// Send a user message containing the URL of a web page.
UserMessageParams params = new UserMessageParams()
        .setMessage("sendbird.com")
        ...

groupChannel.sendUserMessage(params, new BaseChannel.SendUserMessageHandler() {
    @Override
    public void onSent(UserMessage userMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
    }
});
Light Color Skin
Copy
// Receive a user message containing OG metadata of the web page through a channel event handler.
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel channel, BaseMessage message) {
        final OGMetaData ogMetaData = message.getOgMetaData();
        if (ogMetaData == null) {
            // The getOgMetaData() returns null if the message doesn’t have an OGMetadata object yet.
            return;
        } else {
            // TODO: Your custom implementation for the Open Graph metadata of the message. 
            String url = ogMetaData.getUrl();
            int width = ogMetaData.getWidth();
            ...

        }
        ...
    
    }

    @Override
    public void onMessageUpdated(BaseChannel channel, BaseMessage message) {
        final OGMetaData ogMetaData = message.getOgMetaData();
        if (ogMetaData == null) {
            return;
        } else {
            // TODO: Your custom implementation for the Open Graph metadata of the message. 
            String url = ogMetaData.getUrl();
            int width = ogMetaData.getWidth();
            ...

        }
        ...

    }
});

Categorize channels by custom type

When creating a channel, you can additionally specify a custom channel type for further channel grouping. This custom type takes on the form of a String, and can be useful in searching or filtering channels.

Note: The DATA and CUSTOM_TYPE are both String fields that allow you to append information to your channels. As mentioned above, a common use case for the CUSTOM_TYPE is to contain information for channel grouping (for example, categorizing into School and Work channels). However, both these fields can be flexibly utilized.

Light Color Skin
Copy
List<String> users = new ArrayList<>();
users.add("Tyler");
users.add("Nathan");

GroupChannelParams params = new GroupChannelParams()
        .setName(NAME)
        .setCustomType(CUSTOM_TYPE)
        ...

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

To get a channel's custom type, use the groupChannel.getCustomType() method.


Categorize messages by custom type

When sending a message, you can addtionally specify a custom message type for further message grouping. This custom type takes on the form of a String, and can be useful in searching or filtering messages.

Note: The DATA and CUSTOM_TYPE are both String fields that allow you to append information to your messages. As mentioned above, a common use case for the CUSTOM_TYPE is to contain information for message grouping (for example, categorizing into Notes and Contacts messages). However, both these fields can be flexibly utilized.

To embed a custom type into a message, set a value of the type to a UserMessageParams or FileMessageParams object, and then pass the object as an argument to a parameter in the sendUserMessage() or sendFileMessage() methods.

Light Color Skin
Copy
UserMessageParams params = new UserMessageParams()
        .setMessage(TEXT_MESSAGE)
        .setCustomType(CUSTOM_TYPE)
        ...

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

To get a message's custom type, use the message.getCustomType() method.


Search channels by name, URL, or other filters

You can search for specific group channels by adding keywords to a GroupChannelListQuery instance. There are two types of keywords: a Name and a URL. The code sample below shows the query instance which returns a list of the current user's group channels that partially match the specified Name keyword in the names of the channels.

Light Color Skin
Copy
myChannelListQuery = GroupChannel.createMyGroupChannelListQuery();
myChannelListQuery.setIncludeEmpty(true);
myChannelListQuery.setChannelNameContainsFilter("SendBird");

myChannelListQuery.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
    @Override
    public void onResult(List<GroupChannel> groupChannels, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
        // A list of group channels that have "SendBird" in their names is returned.
    }
});

The following shows the query instance which returns a list of the current user's group channels that partially match the specified URL keywords in the URLs of the channels.

Light Color Skin
Copy
myChannelListQuery = GroupChannel.createMyGroupChannelListQuery();
myChannelListQuery.setIncludeEmpty(true);

List<String> channelUrls = new ArrayList<>();
channelUrls.add("seminar");
channelUrls.add("lecture");

myChannelListQuery.setChannelUrlsFilter(channelUrls);

myChannelListQuery.next(new GroupChannelListQuery.GroupChannelListQueryResultHandler() {
    @Override
    public void onResult(List<GroupChannel> groupChannels, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
        // A list of group channels that have "seminar" or "lecture" in their URLs is returned.
    }
});

The following table shows all the supported filters for GroupChannelListQuery to search for group channels you want to retrieve. You can use any filters in a similar fashion with the sample code above.

NameFilters...

CustomTypesFilter

Group channels with the specified one or more custom types. You can enable this filter using the setCustomTypesFilter() method.

CustomTypeStartsWithFilter

Group channels with the custom type which starts with the specified value. You can enable this filter using the setCustomTypeStartsWithFilter() method.

ChannelNameContainsFilter

Group channels that contain the specified value in their names. You can enable this filter using the setChannelNameContainsFilter() method.

ChannelUrlsFilter

Group channels with the specified one or more channel URLs. You can enable this filter using the setChannelUrlsFilter() method.

SuperChannelFilter

Either super or nonsuper group channels. Using the setSuperChannelFilter() method, you can enable this filter.

PublicChannelFilter

Either public or private group channels. Using the setPublicChannelFilter() method, you can enable this filter.

UnreadChannelFilter

Group channels with one or more unread messages. Using the setUnreadChannelFilter() method, you can enable this filter.

HiddenChannelFilter

Group channels with the specified state and operating behavior. You can enable this filter using the setHiddenChannelFilter() method.

MemberStateFilter

Group channels based on whether or not the user has accepted an invitation, or whether or not the user was invited by a friend. You can enable this filter using the setMemberStateFilter() method.

UserIdsExactFilter

Group channels where the members with the specified one or more user IDs are exactly in. You can enable this filter using the setUserIdsExactFilter() method.

UserIdsIncludeFilter

Group channels that include one or more members with the specified user IDs. You can enable this filter using the setUserIdsIncludeFilter() method.

NicknameContainsFilter

Group channels with members whos nicknames contain the specified value. You can enable this filter using the setNicknameContainsFilter() method.

MetaDataOrderKeyFilter

Group channels with metadata containing an item with the specified value as its key. This filter is effective only when the metadata are sorted in the alphabetical order. You can enable this filter using the setMetaDataOrderKeyFilter() method.


Generate thumbnails of a file message

When sending an image file, you can determine whether to create thumbnails of the image to 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 Chat SDK doesn't support creating thumbnails when sending a file message via a file URL.

The sendFileMessage() method requires passing a FileMessageParams object as an argument to a parameter, containing an array of items which each specify the maximum values of width and height of a thumbnail image. The callback function subsequently returns a list of Thumbnail items that each contain the URL of the generated thumbnail image file.

Light Color Skin
Copy
// Creating and adding a ThumbnailSize object (allowed number of thumbnail images: 3).
List<FileMessage.ThumbnailSize> thumbnailSizes = new ArrayList<>();
thumbnailSizes.add(new ThumbnailSize(100,100));
thumbnailSizes.add(new ThumbnailSize(200,200));

FileMessageParams params = new FileMessageParams()
        ...
        .setFile(FILE)
        .setFileName(FILE_NAME)
        .setFileSize(FILE_SIZE)
        .setMimeType(MIME_TYPE)
        .setThumbnailSizes(thumbnailSizes);

groupChannel.sendFileMessage(params, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        if (e != null) {    // Error.
            return;
        }
        
        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(); // The URL of first thumbnail file.
        String urlSecond = second.getUrl(); // The URL of second thumbnail file.
    }
});

A thumbnail image is generated evenly to fit within the bounds of (maxWidth, maxHeight), which are provided through the ThumbnailSize constructor. 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 Sendbird server.

This is one of Sendbird's premium features. Contact our sales team for further assistance.


Track file upload progress using a handler

You can track the file upload progress by passing the SendFileMessageWithProgressHandler() as an argument to a parameter when calling the sendFileMessage() method.

Light Color Skin
Copy
FileMessageParams params = new FileMessageParams(FILE)
        .setFileName(FILE_NAME)
        .setData(DATA)
        .setCustomType(CUSTOM_TYPE);

FileMessage fileMessage = groupChannel.sendFileMessage(params, new BaseChannel.SendFileMessageWithProgressHandler() {
    @Override
    public void onProgress(int bytesSent, int totalBytesSent, int totalBytesToSend) {   // Check progress of file upload here.
        int percent = (totalBytesSent * 100) / totalBytesToSend;
    }

    @Override
    public void onSent(FileMessage message, SendBirdException e) {
        if (e != null) {    // Error.
            // Do something when an error happens.
        } else {
            // Do something with the sent file message.
        }
    }
});

Cancel an in-progress file upload

Using the cancelFileMessageUpload() method, you can cancel an in-progress file upload while it's not completed yet. If the function operates successfully, true is returned.

Note: If you attempt to cancel the uploading after it is already completed, or canceled, or returned an error, the function returns false.

Light Color Skin
Copy
FileMessageParams params = new FileMessageParams(FILE)
        .setFileName(FILE_NAME)
        .setData(DATA)
        .setCustomType(CUSTOM_TYPE);

FileMessage fileMessage = groupChannel.sendFileMessage(params, new BaseChannel.SendFileMessageHandler() {
    @Override
    public void onSent(FileMessage fileMessage, SendBirdException e) {
        ...
    }
});

// Cancel uploading a file in the file message.
boolean isCanceled = groupChannel.cancelFileMessageUpload(fileMessage.getRequestId());

Share an encrypted file with other members

This file encryption feature prevents users without access from opening and reading encrypted files that have been shared within a group of users. When this feature is turned on, all types of sent files and thumbnail images will be first uploaded to Sendbird server, and then encrypted by AES256.

In a group channel, encrypted files and thumbnail images will be decrypted and accessed securely only by the members. Anyone outside of the channel and application will not have access to those files and thumbnail images. The following explains how this data security works and what to do at the SDK level to apply it to your client apps.

The Sendbird system enables secure encryption and decryption of files by generating and distributing an opaque and unique encryption key for each user. An encryption key is managed internally by the system, and is valid for 3 days. It is generated every time the user logs in to Sendbird server through the Chat SDK, which then gets delivered to the Chat SDK from the server.

When the Chat SDK requests an encrypted file by its URL, the parameter auth should be added to the URL to access the file, which is specified with an encryption key of the user such as ?auth=RW5jb2RlIHaXMgdGV4eA==. With the specified key in the auth, Sendbird server first decrypts the file, then checks if the user is a member of the group channel, and finally, allows the user to access and open the file in the channel.

This can be easily done by using the fileMessage.getUrl() method, which automatically adds the parameter auth with an encryption key of the current user to the file URL, and returns the unique URL for the user.


Spam flood protection

This feature allows you to customize the number of messages a member can send in a group channel per second. By doing so, all excess messages will be deleted and only the number of messages allowed to be sent per member per second will be delivered. This feature protects your app from some members spamming others in the channel with the same messages.

Note: Our default system setting is 5 messages per second. This limit can be manually adjusted only from our side. This is one of Sendbird's premium features. Contact our sales team for further assistance.


Message auto-translation

It is possible for text messages to be sent in different languages through the Sendbird's auto-translation feature. When sending a text message, set a List of language codes to a UserMessageParams object and then pass the object as an argument to a parameter in the sendUserMessage() method to request translated messages in the corresponding languages.

Note: This message auto-translation feature is powered by Google Cloud Translation API recognition engine and Microsoft Translator engine. It is by default that Google's Cloud Translation API recognition engine is used for message auto-translation, whereas if your Sendbird application has been created before June 26, 2019, Microsoft Translator engine is used.

Light Color Skin
Copy
List<String> translationTargetLanguages = new ArrayList<>();
translationTargetLanguages.add("es");   // Spanish
translationTargetLanguages.add("ko");   // Korean

UserMessageParams params = new UserMessageParams()
        .setMessage(TEXT_MESSAGE)
        .setCustomType(CUSTOM_TYPE)
        .setData(DATA)
        ...
        .setTranslationTargetLanguages(translationTargetLanguages);

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

You can retrieve translations of a text message using the userMessage.getTranslations() method which returns a Map object containing the language codes and translations.

Note: The two translation engines support a wide variety of languages, and you can see their language code tables in the Miscellaneous > Language support section.

Light Color Skin
Copy
SendBird.addChannelHandler(UNIQUE_HANDLER_ID, new SendBird.ChannelHandler() {
    @Override
    public void onMessageReceived(BaseChannel channel, BaseMessage message) {
        Map<String, String> map = ((UserMessage) message).getTranslations();
        String esTranslatedMessage = map.get("es");     // Spanish
        ...
        // TODO: Display translation in UI.
    }
});

This is one of Sendbird's premium features. Contact our sales team for further assistance.


Message on-demand translation

Using the groupChannel.translateUserMessage() method, you can allow your users to translate text messages into other languages when needed.

Note: This message on-demand translation is powered by Google Cloud Translation API recognition engine, and you can see its language code table in the Miscellaneous > Language support section.

Light Color Skin
Copy
List<String> translationTargetLanguages = new ArrayList<>();
translationTargetLanguages.add("es");   // Spanish
translationTargetLanguages.add("de");   // German 

// The USER_MESSAGE below indicates a UserMessage object which represents an already sent or received text message. 
groupChannel.translateUserMessage(USER_MESSAGE, translationTargetLanguages, new BaseChannel.TranslateUserMessageHandler() {
    @Override
    public void onTranslated(UserMessage userMessage, SendBirdException e) {
        Map<String, String> map = userMessage.getTranslations();
        String esTranslatedMessage = map.get("es");     // Spanish
        String deTranslatedMessage = map.get("de");     // German 
        ...
        // Display translation in UI.
    }
}

Based on this method, you can implement features such as real-time or instant translation to your app. You can also implement to only translate a selected message into preferred languages.

This is one of Sendbird's premium features. Contact our sales team for further assistance.