Manage chat groups
Updated
Introduces chat group functionalities.
Chat groups enable real-time messaging among multiple users.
This page shows how to use the Chat SDK to create and manage a chat group in your app.
Understand the tech
The Chat SDK provides the Group, GroupManager, and GroupChangeListener classes for chat group management, which allows you to implement the following features:
- Create and destroy a chat group
- Join and leave a chat group
- Retrieve the member list of a chat group
- Block and unblock a chat group
- Listen for the chat group events
Prerequisites
Before proceeding, ensure that you meet the following requirements:
- You have initialized the Chat SDK. For details, see SDK quickstart.
- You understand the call frequency limits of the Chat APIs supported by different pricing plans as described in Limitations.
- You understand the number of chat groups and chat group members supported by different pricing plans as described in Pricing Plan Details.
Implementation
This section describes how to call the APIs provided by the Chat SDK to implement features.
Create and destroy a chat group
Users can create a chat group and set the chat group attributes such as the name, description, group members, and reasons for creating the group. Users can also set the GroupOptions parameter to specify the size and type of the chat group. Once a chat group is created, the creator of the chat group automatically becomes the chat group owner.
Only chat group owners can disband chat groups. Once a chat group is disbanded, all members of that chat group receive the onGroupDestroyed callback and are immediately removed from the chat group. All local data for the chat group is also removed from the database and memory.
Refer to the following sample code to create and destroy a chat group:
GroupOptions option = new GroupOptions();
// Set the size of a chat group to 100 members.
option.maxUsers = 100;
// Set the type of a chat group to private. Allow chat group members to invite other users to join the chat group.
option.style = GroupStyle.GroupStylePrivateMemberCanInvite;
// Call createGroup to create a chat group.
ChatClient.getInstance().groupManager().createGroup(groupName, desc, allMembers, reason, option);
// Call destroyGroup to disband a chat group.
ChatClient.getInstance().groupManager().destroyGroup(groupId);Join and leave a chat group
Users can request to join a public chat group as follows:
- Call
getPublicGroupsFromServerto retrieve the list of public groups by page. Users can obtain the ID of the group that they want to join. - Call
joinGroupto send a join request to the chat group:- If the type of the chat group is set to
GroupStylePublicJoin, the request from the user is accepted automatically and the other chat group members receive theonMembersJoinedcallback. - If the type of the chat group is set to
GroupStylePublicNeedApproval, the chat group owner and chat group admins receive theonRequestToJoinReceivedcallback and determine whether to accept the request from the user.
- If the type of the chat group is set to
Users can call leaveGroup to leave a chat group. Once a user leaves the group, all the other group members receive the onMembersExited callback.
Refer to the following sample code to join and leave a chat group:
// List public groups by page.
CursorResult result = ChatClient.getInstance().groupManager().getPublicGroupsFromServer(pageSize, cursor);
List groupsList = List returnGroups = result.getData();
String cursor = result.getCursor();
// Call joinGroup to send a join request to a chat group.
ChatClient.getInstance().groupManager().joinGroup(groupId);
// Call leaveGroup to leave a chat group.
ChatClient.getInstance().groupManager().leaveGroup(groupId);Retrieve the member list of a chat group
-
When a group has less than 200 members, you can call the
getGroupFromServermethod to retrieve the group member list that contains the group owner, admins, and regular members.// If `true` is passed to the second parameter, the SDK returns the group member list that contains up to 200 group members. // It is a synchronous method and may block the current thread. Group group = ChatClient.getInstance().groupManager().getGroupFromServer(groupId, true); List memberList = group.getMembers();// gets regular members. memberList.addAll(group.getAdminList());// gets group admins. memberList.add(group.getOwner());// gets the group owner. -
When a group has more than 200 members, you can first call the
getGroupFromServermethod to get the group member list that contains the group owner and admins and then call thefetchGroupMembersmethod to obtain the list of regular group members.// If `true` is passed to the second parameter, the SDK returns the group member list that contains up to 200 group members. // It is a synchronous method and may block the current thread. Group group = ChatClient.getInstance().groupManager().getGroupFromServer(groupId, true); List memberList = new ArrayList<>(); CursorResult result = null; final int pageSize = 20; do { // It is a synchronous method and may block the current thread. The asynchronous method is asyncFetchGroupMembers(String, String, int, ValueCallBack). result = ChatClient.getInstance().groupManager().fetchGroupMembers(groupId, result != null? result.getCursor(): "", pageSize); memberList.addAll(result.getData()); } while (!TextUtils.isEmpty(result.getCursor()) && result.getData().size() == pageSize); memberList.addAll(group.getAdminList());// gets group admins. memberList.add(group.getOwner());// gets the group owner. -
Since SDK v1.4.0, you can call the
asyncFetchGroupMembersInfomethod to retrieve detailed information about all group members (including the group owner and admins), such as each member's user ID, the time they joined the group, and their role.// The second parameter is the cursor for pagination; pass null for the first page. // The third parameter is the number of members to retrieve per page. ChatClient.getInstance().groupManager().asyncFetchGroupMembersInfo(groupId, null, 50, new ValueCallBack<CursorResult<GroupMemberInfo>>() { @Override public void onSuccess(CursorResult<GroupMemberInfo> value) { List<GroupMemberInfo> list = value.getData(); for (GroupMemberInfo groupMemberInfo : list) { // Get the member's user ID, join time, and role. String id = groupMemberInfo.getMemberId(); long joinTime = groupMemberInfo.getJoinTime(); Group.GroupPermissionType role = groupMemberInfo.getRole(); } } @Override public void onError(int error, String errorMsg) { } });
Retrieve the chat group list
-
Users can call
getJoinedGroupsFromServerto retrieve a list of groups they have joined and created from the server.// Asynchronous method. The synchronous method is getJoinedGroupsFromServer(int, int, boolean, boolean). // pageIndex: Current page index, starting from 0. // pageSize: The number of groups expected per page. The range is [1,20]. List grouplist = ChatClient.getInstance().groupManager().asyncGetJoinedGroupsFromServer(pageIndex, pageSize, needMemberCount, needRole, new ChatValueCallBack>() { @Override public void onSuccess(List value) { } @Override public void onError(int error, String errorMsg) { } }); -
Users can call
getAllGroupsto load the local group list. To ensure the accuracy of results, retrieve the joined chat group list from the server first.List grouplist = ChatClient.getInstance().groupManager().getAllGroups(); -
Users can also retrieve the public chat group list from the server with pagination:
// Synchronous method, which will block the current thread. The asynchronous method is asyncGetPublicGroupsFromServer(int, String, ChatValueCallBack). ChatCursorResult result = ChatClient.getInstance().groupManager().getPublicGroupsFromServer(pageSize, cursor); List groupsList = result.getData(); String cursor = result.getCursor();
Retrieve the number of groups joined by the current user
Users can call the asyncGetJoinedGroupsCountFromServer to retrieve the number of groups they have joined directly from the server. The limit on the number of groups a user can join is determined by the pricing package. For more details, please refer to the product pricing.
ChatClient.getInstance().groupManager().asyncGetJoinedGroupsCountFromServer(new ValueCallBack() {
@Override
public void onSuccess(Integer integer) {
showToast("success: " + integer);
}
@Override
public void onError(int code, String error) {
showToast("error: " + error);
}
});Block and unblock a chat group
All chat group members can block and unblock a chat group. Once a member block a chat group, they no longer receive messages from this chat group.
Refer to the following sample code to block and unblock a chat group:
// Call blockGroupMessage to block a chat group.
ChatClient.getInstance().groupManager().blockGroupMessage(groupId);
// Call unblockGroupMessage to unblock a chat group.
ChatClient.getInstance().groupManager().unblockGroupMessage(groupId);Listen for chat group events
To monitor the chat group events, users can listen for the callbacks in the GroupManager class and add app logics accordingly. If a user wants to stop listening for the callbacks, make sure that the user removes the listener to prevent memory leakage.
Refer to the following sample code to listen for chat group events:
GroupChangeListener groupListener = new GroupChangeListener() {
// Occurs when an invitee receives a group invitation.
@Override
public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
}
// Occurs when a user sends a join request to a chat group.
@Override
public void onRequestToJoinReceived(String groupId, String groupName, String applyer, String reason) {
}
// Occurs when the chat group owner or admin approves a join request.
@Override
public void onRequestToJoinAccepted(String groupId, String groupName, String accepter) {
}
// Occurs when the chat group owner or admin rejects a join request.
@Override
public void onRequestToJoinDeclined(String groupId, String groupName, String decliner, String reason, String applicant) {
}
// Occurs when an invitee accepts a group invitation.
@Override
public void onInvitationAccepted(String groupId, String inviter, String reason) {
}
// Occurs when an invitee declines a group invitation.
@Override
public void onInvitationDeclined(String groupId, String invitee, String reason) {
}
// Occurs when a member is removed from a chat group.
@Override
public void onUserRemoved(String groupId, String groupName) {
}
// Occurs when the chat group owner disbands a chat group.
@Override
public void onGroupDestroyed(String groupId, String groupName) {
}
// Occurs when an invitee accepts a group invitation automatically.
@Override
public void onAutoAcceptInvitationFromGroup(String groupId, String inviter, String inviteMessage) {
}
// Occurs when a member is added to the chat group mute list.
@Override
public void onMuteListAdded(String groupId, final List mutes, final long muteExpire) {
}
// Occurs when a member is removed from the chat group mute list.
@Override
public void onMuteListRemoved(String groupId, final List mutes) {
}
// Occurs when a member is added to the chat group allow list.
@Override
public void onWhiteListAdded(String groupId, List whitelist) {
}
// Occurs when a member is removed from the chat group allow list.
@Override
public void onWhiteListRemoved(String groupId, List whitelist) {
}
// Occurs when all chat group members are muted or unmuted.
@Override
public void onAllMemberMuteStateChanged(String groupId, boolean isMuted) {
}
// Occurs when a member is added to the chat group admin list.
@Override
public void onAdminAdded(String groupId, String administrator) {
}
// Occurs when an admin is removed from the chat group admin list.
@Override
public void onAdminRemoved(String groupId, String administrator) {
}
// Occurs when the chat group owner is changed.
@Override
public void onOwnerChanged(String groupId, String newOwner, String oldOwner) {
}
// Occurs when one or more members join the chat group. All group members except the new members receive this callback.
// Available since SDK v1.4.0.
@Override
public void onMembersJoined(final String groupId, final List<String> members) {
}
// Occurs when a user joins a chat group.
// Deprecated since SDK v1.4.0. Use onMembersJoined instead.
@Deprecated
@Override
public void onMemberJoined(final String groupId, final String member){
}
// Occurs when one or more members leave the chat group, actively or passively. All group members except those who left receive this callback.
// Available since SDK v1.4.0.
@Override
public void onMembersExited(final String groupId, final List<String> members) {
}
// Occurs when a member leaves a chat group.
// Deprecated since SDK v1.4.0. Use onMembersExited instead.
@Deprecated
@Override
public void onMemberExited(final String groupId, final String member) {
}
// Occurs when a member updates the chat group announcement.
@Override
public void onAnnouncementChanged(String groupId, String announcement) {
}
// Occurs when the chat group details, such as the name, description, or avatar, change.
@Override
public void onSpecificationChanged(Group group) {
}
// Occurs when a member uploads a chat group shared file.
@Override
public void onSharedFileAdded(String groupId, MucSharedFile sharedFile) {
}
// Occurs when a member deletes a chat group shared file.
@Override
public void onSharedFileDeleted(String groupId, String fileId) {
}
};
// Add the group listener.
ChatClient.getInstance().groupManager().addGroupChangeListener(groupListener);
// Remove the group listener if not use.
ChatClient.getInstance().groupManager().removeGroupChangeListener(groupListener);