Manage chat rooms

Updated

Shows how to use the Agora Chat SDK to create and manage a chat room in your app.

Chat rooms enable real-time messaging among multiple users.

A chat room does not have a strict membership, and members do not retain any permanent relationship with each other. Once going offline, chat room members cannot receive any messages from the chat room and automatically leave the chat room after 2 minutes (members on the chat room allow list remain in the chat room even if they stay offline for 2 minutes or more). A chat room is widely applied in live broadcast use cases such as stream chat in Twitch.

This page shows how to use the Chat SDK to create and manage a chat room in your app.

Understand the tech

The Chat SDK provides the ChatManager and ChatRoom classes for chat room management, which allows you to implement the following features:

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 limit of the Chat APIs supported by different pricing plans as described in Limitations.
  • You understand the number of chat rooms supported by different pricing plans as described in Pricing Plan Details.
  • Only the app super admin has the privilege of creating a chat room. Ensure that you have added an app super admin by calling the super-admin RESTful API.

Implementation

This section introduces how to call the APIs provided by the Chat SDK to implement the features listed above.

Create and destroy a chat room

The app super admin can call createChatRoom to create a chat room and set the chat room attributes such as the chat room subject, description, and the maximum number of members.

You are advised to call the RESTful API to create a chat room from the server.

// The app super admin calls createChatRoom to create a chat room.
// Once the chat room is created, the super admin becomes the chat room owner.
ChatRoom  chatRoom = ChatClient.getInstance().chatroomManager().createChatRoom(subject, description, welcomMessage, maxUserCount, members);

// Only the chat room owner can call destroyChatRoom to disband the chat room.
// Once the chat room is disbanded, all the chat room members receive the onChatRoomDestroyed callback and are immediately removed from the chat room.
ChatClient.getInstance().chatroomManager().destroyChatRoom(chatRoomId);

Join and leave a chat room

All the chat users can all joinChatRoom to join the specified chat room.

// Once the chat user successfully joins the chat room, all the other chat room members receive the onMemberJoined callback.
ChatClient.getInstance().chatroomManager().joinChatRoom(chatRoomId, new ValueCallBack() {
    @Override
    public void onSuccess(ChatRoom value) {

    }

    @Override
    public void onError(int error, String errorMsg) {

    }
});

// All the chat room members can call leaveChatRoom to leave the specified chat room. Once a member leaves the chat room, all the other members receive the onMemberExited callback.
ChatClient.getInstance().chatroomManager().leaveChatRoom(chatRoomId);

By default, when you leave a chat room, the SDK removes all the chat room messages on the local device. If you do not want these messages removed, set setDeleteMessagesAdExitChatRoom in ChatOptions as false.

Retrieve the chat room list and attributes

All chat users can get the chat room list from the server and retrieve the basic information of the specified chat room using the chat room ID.

// Chat room members can call fetchPublicChatRoomsFromServer to get the specified number of chat rooms from the server. The maximum value of pageSize is 100.
PageResult chatRooms = ChatClient.getInstance().chatroomManager().
                            fetchPublicChatRoomsFromServer(pageNumber, pageSize);

// Chat room members can call fetchChatRoomFromServer to get the basic information of the specified chat room by passing the chat room ID.
ChatRoom chatRoom = ChatClient.getInstance().chatroomManager().fetchChatRoomFromServer(chatRoomId);

Listen for chat room events

To monitor the chat room events, you can listen for the callbacks in the ChatRoomManager class and add app logics accordingly. If you want to stop listening for the callback, make sure that you remove the listener to prevent memory leakage.

public interface ChatRoomChangeListener {
    /**
     * Occurs when the chat room instance is destroyed.
     *
     * @param roomId        The chat room ID
     * @param roomName      The chat room name
     */
    void onChatRoomDestroyed(final String roomId, final String roomName);

    /**
     * Occurs when a new member joins the chat room.
     *
     * @param roomId        The chat room ID
     * @param participant   The username of the new chat room member
     */
    void onMemberJoined(final String roomId, final String participant);

    /**
     * Occurs when a member leaves the chat room.
     *
     * @param roomId        The chat room ID
     * @param roomName      The chat room name
     * @param participant   The username of the member that leaves the chat room
      */
    void onMemberExited(final String roomId, final String roomName, final String participant);

    /**
     * Occurs when a chat room member is removed.
     *
     * @param reason        The reason why this member is removed, either being kicked by the chat room admin, or being offline due to network conditions
     * @param roomId        The chat room ID
     * @param roomName      The chat room name
     * @param participant   The username of the member that is removed from the chat room
     */
    void onRemovedFromChatRoom(final int reason, final String roomId, final String roomName, final String participant);

    /**
     * Occurs when members are added to the chat room mute list. The muted members receive this event.
     *
     * <p>Available since SDK v1.4.0.
     *
     * @param chatRoomId    The chat room ID
     * @param muteInfo      A map of the muted members' user IDs to their mute expiration timestamps (Unix timestamps in milliseconds)
     */
    void onMuteListAdded(final String chatRoomId, final Map<String, Long> muteInfo);

    /**
     * Occurs when a member is added to the chat room mute list.
     *
     * @param chatRoomId    The chat room ID
     * @param mutes         The usernames of the members added to the chat room mute list
     * @param expireTime    The Unix timestamp when the mute expires, in milliseconds
     * @deprecated Deprecated since SDK v1.4.0. Use {@link #onMuteListAdded(String, Map)} instead.
     */
    @Deprecated
    void onMuteListAdded(final String chatRoomId, final List mutes, final long expireTime);

    /**
     * Occurs when a member is removed from the chat room mute list.
     *
     * @param chatRoomId    The chat room ID
     * @param mutes         The usernames of the members removed from the chat room mute list
     */
    void onMuteListRemoved(final String chatRoomId, final List mutes);

    /**
     * Occurs when a member is added to the chat room allow list.
     *
     * @param chatRoomId    The chat room ID
     * @param whitelist     The usernmaes of the members added to the chat room allow list
     */
    void onWhiteListAdded(final String chatRoomId, final List whitelist);

    /**
     * Occurs when a member is removed from the chat room allow list.
     *
     * @param chatRoomId    The chat room ID
     * @param whitelist     The usernames of the members removed from the chat room allow list
     */
    void onWhiteListRemoved(final String chatRoomId, final List whitelist);

    /**
     * Occurs when the state of muting all the chat room members changes.
     *
     * @param chatRoomId    The chat room ID
     * @param isMuted       Whether all the chat room members are muted
     */
    void onAllMemberMuteStateChanged(final String chatRoomId, final boolean isMuted);

    /**
     * Occurs when a member is added to the chat room admin list.
     *
     * @param chatRoomId    The chat room ID
     * @param admin         The username of the chat room member added to the admin list
     */
    void onAdminAdded(final String chatRoomId, final String admin);

    /**
     * Occurs when a member is removed from the chat room admin list.
     *
     * @param  chatRoomId   The chat room ID
     * @param  admin        The username of the chat name member removed from the admin list
     */
    void onAdminRemoved(final String chatRoomId, final String admin);

    /**
     * Occurs when the chat room ownership is transferred.
     *
     * @param chatRoomId    The chat room ID
     * @param newOwner      The username of the new chat room owner
     * @param oldOwner      The username of the original chat room owner
     */
    void onOwnerChanged(final String chatRoomId, final String newOwner, final String oldOwner);

    /**
     * Occurs when the chat room announcement is changed.
     * @param chatRoomId    The chat room ID
     * @param announcement  The new chat room announcements
     */
    void onAnnouncementChanged(String chatRoomId, String announcement);
}

// Occurs when custom chat room attributes are changed.
default void onChatroomAttributesDidChanged(String chatRoomId, Map attributeMap , String from){}

// Occurs when custom chat room attributes are removed.
default void onChatroomAttributesDidRemoved(String chatRoomId, List keyList , String from){}

// Adds a chat room listener to monitor chat room callback events.
ChatClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);

// Removes the chat room listener.
ChatClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomChangeListener);

Update the chat room member count in real time

If many members join or leave a chat room in a very short time, you can update the chat room member count in real time:

  1. When a user joins a chat room, other members in the chat room receive the onMemberJoined event. When a member leaves or is removed from a chat room, other members in the chat room receive the onMemberExited or onRemovedFromChatRoom event.

  2. After the event is received, you can call the getChatRoom method to get local details of the chat room and call the ChatRoom#getMemberCount method to get the current number of members in the chat room.

    ChatClient.getInstance().chatroomManager().addChatRoomChangeListener(new ChatRoomChangeListener() {
    
            @Override
            public void onMemberJoined(String roomId, String participant) {
                //Get the current number of members in the chat room.
                ChatClient.getInstance().chatroomManager().getChatRoom(roomId).getMemberCount();
            }
    
            @Override
            public void onMemberExited(String roomId, String roomName, String participant) {
                //ChatClient.getInstance().chatroomManager().getChatRoom(roomId).getMemberCount();
            }
    
        });