# Manage local conversations (/en/realtime-media/im/build/build-core-messaging/messages/manage-messages/android)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

In chat apps, a conversation is composed of all the messages in a peer-to-peer chat, chat group, or chatroom. The Chat SDK supports managing messages by conversations, including retrieving and managing unread messages, deleting the historical messages on the local device, and searching historical messages.

    This page introduces how to use the Chat SDK to implement these functionalities.

    ## Understand the tech [#understand-the-tech-1]

    SQLCipher is used to encrypt the database that stores local messages. The Chat SDK uses `ChatManager` to manage local messages. The following are the core methods:

    * `getAllConversationsBySort`: Loads the conversation list on the local device.
    * `Conversation.getUnreadMsgCount`: Retrieves the count of unread messages in the specified conversation.
    * `getUnreadMessageCount`: Retrieves the count of all unread messages.
    * `asyncPinConversation`: Pins a conversation.
    * `asyncFetchPinnedConversationsFromServer`: Retrieves the pinned conversations from the server with pagination.
    * `searchMsgFromDB`: Searches for messages from the local database.
    * `Conversation.insertMessage`: Inserts messages in the specified conversation.
    * `asyncDeleteAllMsgsAndConversations`: Clears the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms. You can also choose whether to clear the chat history on the server in one direction.
    * `clearAllMessages`: Deletes all messages of the local specified conversation.
    * `removeMessages`: Deletes local messages in the specified time period.
    * `removeMessage`: Deletes the specified message of a single local conversation.

    ## Prerequisites [#prerequisites-1]

    Before proceeding, ensure that you meet the following requirements:

    * You have integrated the Chat SDK, initialized the SDK and implemented the functionality of registering accounts and login. For details, see [Chat SDK quickstart](../../../../get-started-sdk).
    * You understand the API call frequency limits as described in [Limitations](../../limitations).

    ## Implementation [#implementation-1]

    This section shows how to implement managing messages.

    ### Retrieve conversations [#retrieve-conversations-1]

    You can call the `getAllConversationsBySort` method to get all local conversations. The SDK first retrieves the conversations from the memory. If no conversation is loaded from the local database, the SDK will load the conversations to the memory. The SDK returns the conversation list in the reverse chronological order of when conversations are active (the timestamp of the last message in the conversation), with the pinned conversations coming before the unpinned ones. The conversation list is of the `List` structure:

    ```java
    List conversations = ChatClient.getInstance().chatManager().getAllConversationsBySort();
    ```

    ### Retrieve messages in the specified conversation [#retrieve-messages-in-the-specified-conversation]

    Call `getAllMessages` to retrieve all the messages of this conversation in the memory. Alternatively, you can call `loadMoreMsgFromDB` to load messages from the local database. The loaded message will be placed in the memory based on the timestamp of the messages.

    ```java
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);

    List messages = conversation.getAllMessages();
    // startMsgId: Starting message ID for query. The SDK loads messages, starting from the specified one, in the descending order of the timestamp included in the messages.
    // pageSize: Number of message to load on each page. The value range is [1,400].
    List messages = conversation.loadMoreMsgFromDB(startMsgId, pagesize);
    ```

    ### Retrieve the count of unread messages in the specified conversation [#retrieve-the-count-of-unread-messages-in-the-specified-conversation]

    Refer to the following code example to retrieve the count of unread messages:

    ```java
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    conversation.getUnreadMsgCount();
    ```

    ### Retrieve the count of unread messages in all conversations [#retrieve-the-count-of-unread-messages-in-all-conversations]

    Refer to the following code example to retrieve the count of all unread messages:

    ```java
    ChatClient.getInstance().chatManager().getUnreadMessageCount();
    ```

    ### Mark unread messages as read [#mark-unread-messages-as-read]

    Refer to the following code example to mark the specified messages as read:

    ```java
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    // Mark all the messages in the current conversation as read.
    conversation.markAllMessagesAsRead();
    // Mark the specified message as read.
    conversation.markMessageAsRead(messageId);
    // Mark all unread messages as read.
    ChatClient.getInstance().chatManager().markAllConversationsAsRead();
    ```

    ### Clear chat history [#clear-chat-history-1]

    To clear the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms, you can call the `ChatManager#asyncDeleteAllMsgsAndConversations` method. Additionally, you can choose whether to clear the chat history on the server. Note that clearing the chat history on the server means that you will not be able to retrieve conversations and messages from the server, although other users will not be affected.

    ```java
    boolean clearServerData=true;
    ChatClient.getInstance().chatManager().asyncDeleteAllMsgsAndConversations(clearServerData, new CallBack() {
        @Override
        public void onSuccess() {

        }

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

        }
    });
    ```

    ### Delete all messages in a local conversation [#delete-all-messages-in-a-local-conversation]

    You can call `clearAllMessages` to delete all messages sent and received in a local conversation:

    ```java
    // conversationId: The conversation ID, which is the user ID of the peer user in one-to-one chat, group ID in group chat, and chat room ID in room chat.
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    if(conversation != null) {
        conversation.clearAllMessages();
    }
    ```

    ### Delete messages in a local conversation by time period [#delete-messages-in-a-local-conversation-by-time-period]

    You can call `removeMessages` to delete messages sent and received in a certain period in a local conversation.

    ```java
    // conversationId: The conversation ID, which is the user ID of the peer user in one-to-one chat, group ID in group chat, and chat room ID in room chat.
    // startTime: The starting UNIX timestamp for message deletion.
    // endTime: The end UNIX timestamp for message deletion.
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    if(conversation != null) {
        conversation.removeMessages(startTime, endTime);
    }
    ```

    ### Delete a specific message [#delete-a-specific-message]

    You can delete a specific message from a local conversation. The sample code is as follows:

    ```java
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    if(conversation != null) {
        conversation.removeMessage(messageId);
    }
    ```

    ### Search for messages using keywords [#search-for-messages-using-keywords]

    Search methods provided on this page can be used to search the local database for all types of messages except command messages, because command messages are not stored in the local database.

    Call `searchMsgFromDB` to search for messages by keywords, timestamp, and message sender:

    ```java
    List messages = conversation.searchMsgFromDB(keywords, timeStamp, maxCount, from, Conversation.SearchDirection.UP);
    ```

    ### Search for messages in all conversations based on search scope [#search-for-messages-in-all-conversations-based-on-search-scope]

    You can call the `ChatManager#searchMsgFromDB(String, long, int, String, Conversation.SearchDirection, Conversation.EMMessageSearchScope)` method to search in all conversations based on the search scope. This means that, in addition to setting the keywords, message timestamps, number of messages, sender, and search direction, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```java
    List chatMessages = ChatClient.getInstance().chatManager().searchMsgFromDB("keyword", System.currentTimeMillis(), 100, "message sender id", Conversation.SearchDirection.UP, Conversation.ChatMessageSearchScope.ALL);
    ```

    ### Search for messages in the current conversation based on search scope [#search-for-messages-in-the-current-conversation-based-on-search-scope]

    You can call `Conversation#searchMsgFromDB(String, long, int, String, Conversation.SearchDirection, Conversation.EMMessageSearchScope)` method to search for messages in the current conversation based on the search scope. This means that, in addition to setting keywords, message timestamps, number of messages, sender, direction, and other parameters, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```java
    List chatMessages = ChatClient.getInstance().chatManager().getConversation("conversationId").searchMsgFromDB("keyword", System.currentTimeMillis(), 100, "message sender id", Conversation.SearchDirection.UP, Conversation.ChatMessageSearchScope.ALL);
    ```

    ### Import messages [#import-messages]

    Call importMessages to import multiple messages to the local database.

    ```java
    ChatClient.getInstance().chatManager().importMessages(msgs);
    ```

    ### Insert messages [#insert-messages]

    If you want to insert a message to the current conversation without actually sending the message, construct the message body and call `insertMessage`. This can be used to send notification messages such as "XXX recalls a message", "XXX joins the chat group", and "Typing ...".

    ```java
    // Insert a message to the specified conversation.
    Conversation conversation = ChatClient.getInstance().chatManager().getConversation(conversationId);
    conversation.insertMessage(message);
    // Insert a message.
    // ChatClient.getInstance().chatManager().saveMessage(message);
    ```

    ## Next steps [#next-steps-1]

    After implementing managing messages, you can refer to the following documents to add more messaging functionalities to your app:

    * [Retrieve conversations and messages from the server](./retrieve-messages)
    * [Message receipts](./message-receipts)

    
  
      
  
      
  
      
  
      
  
      
  
