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

To find and chat with other users within the application easily, a user can add friends by using the unique identifiers of other users such as hashed phone numbers for privacy. When the unique identifier, which is used as the discovering keys, linked to a user using our service is uploaded, the SendBird system can match and retrieve the users and then automatically register them as friends.

Note: To use this ability, you should make sure the unique identifiers of every user are registered individually in advance by using the platform API's update a user action.

Light Color Skin
Copy
// Uploading friend discovery keys
Map<String, String> discoveryMap = new HashMap<>();
discoveryMap.put("0001-0002-0003", "John");
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;
        }
    }
});

// Deleting friend discovery keys
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;
        }
    }
});

Or you can make any user add and delete friends by using an array of the IDs of other users like the below.

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

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


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

Using the FriendListQuery's next() method which returns a list of User objects, you can also retrieve a list of friends of the current user.

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 when a user is typing a text message, SendBird server notifies of the event to the client apps of all channel members through the onTypingStatusUpdate() of the registered channel event handler.

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

// To listen for 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 read

To maintain the most up-to-date and accurate read status of messages for each member in a group channel, the markAsRead() method should be called when any one of the members reads messages in the channel by entering the channel from a channel list or making the opened channel view in the background to be active on the screen.

When the markAsRead() is called, SendBird server updates the number of the current user's unread messages both in a group channel and in all joined channels. The server then notifies the change of read status to all the other channel members' client apps through the onReadReceiptUpdated() method of the channel event handler.

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

// To listen for 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.
        }
    }
});

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. A list of the members for each message is depending on the read receipt of each member.

If you want to keep track of who have read a new message, we recommend you implement the getReadMembers() in the onReadReceiptUpdated() method. Then it will receive a callback from SendBird server when any other member has read a message. Afterwards you should pass the newly received message object via the onReadReceiptUpdated() to the getReadMembers() as a parameter.

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

The getReadMembers() returns a list of members who have read a message except the current user and the message sender.

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. And using the getReadStatus() method, you can get a list of information on the read receipt of each member, except the current user. The read receipt indicates the timestamp of when each user has last read the messages in the channel, in Unix milliseconds.


Retrieve number of members who have not 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, you should first update the channel by 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 for 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.
                }
            }
        }
    }
});

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 the SendBird Dashboard or the Platform API. To send an admin message through your dashboard, go to the Moderation > Group Channels panel, 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 Platform 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 engineering 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;
        }
    }
});

// Add 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;
        }
    }
});

// Remove 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;
        }
    }
});

// Delete 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.


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 with other values, and then pass the object as a parameter to 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 way 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 SDK doesn't support creating thumbnails when sending a file message via a file URL.

The sendFileMessage() method requires that you pass a FileMessageParams object as 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
// Create and add 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(); // URL of first thumbnail file.
        String urlSecond = second.getUrl(); // 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 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 is 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 SDK, which then gets delivered to the SDK from the server.

When the 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.

This is one of SendBird's premium features, contact our sales team for further assistance. This feature will also require customized implementation efforts from your side.


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 by our side. You can contact our engineering team about this setting. 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 a parameter to 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
        ...
        // Display translation in UI.
    }
});

Using the groupChannel.translateUserMessage() method, you can also translate an already sent text message into other languages for your specific needs.

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

Note: This is one of SendBird's premium features, contact our sales team for further assistance.