Skip to main content

Documentation Index

Fetch the complete documentation index at: https://cometchat-22654f5b-docs-android-v6-beta2.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

FieldValue
Key ClassesCometChat.MessageListener, MessagesRequestBuilder
Key MethodsaddMessageListener(), fetchPrevious(), fetchNext(), getUnreadMessageCount()
Listener EventsonTextMessageReceived, onMediaMessageReceived, onCustomMessageReceived
PrerequisitesSDK initialized, user logged in
Receiving messages with CometChat has two parts:
  1. Adding a real-time listener to receive messages while your app is running
  2. Fetching missed, unread, or historical messages when your app starts up or the user scrolls back

Real-Time Messages

Register a MessageListener to receive incoming messages as they arrive. For every activity or fragment you wish to receive messages in, register the listener using addMessageListener(). We suggest adding it in the onResume() method.
private String listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(listenerID, new CometChat.MessageListener() {
  @Override
  public void onTextMessageReceived(TextMessage textMessage) {
      Log.d(TAG, "Text message received successfully: " + textMessage.toString());
  }

  @Override
  public void onMediaMessageReceived(MediaMessage mediaMessage) {
      Log.d(TAG, "Media message received successfully: " + mediaMessage.toString());
  }

  @Override
  public void onCustomMessageReceived(CustomMessage customMessage) {
      Log.d(TAG, "Custom message received successfully: " + customMessage.toString());
  }
});
ParameterDescription
listenerIDAn ID that uniquely identifies that listener. We recommend using the activity or fragment name
Remove the listener when you no longer need it. Typically, this can be added in the onPause() method.
private String listenerID = "UNIQUE_LISTENER_ID";

CometChat.removeMessageListener(listenerID);
Always remove listeners when they’re no longer needed (e.g., in onPause()). Failing to do so can cause memory leaks and duplicate event handling.
As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices.

Missed Messages

Fetch messages that arrived while your app was offline. Use getLastDeliveredMessageId() to find where you left off, then call fetchNext() to get everything after that point. Call fetchNext() repeatedly on the same request object to paginate.
private int limit = 30;
private int latestId = CometChat.getLastDeliveredMessageId();
private String UID = "cometchat-uid-1";

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder()
      .setMessageId(latestId)
      .setLimit(limit)
      .setUID(UID)
      .build();

messagesRequest.fetchNext(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List<BaseMessage> list) {
      for (BaseMessage message : list) {
          if (message instanceof TextMessage) {
              Log.d(TAG, "Text message received successfully: " +
                      ((TextMessage) message).toString());
          } else if (message instanceof MediaMessage) {
              Log.d(TAG, "Media message received successfully: " +
                      ((MediaMessage) message).toString());
          }
      }
  }

  @Override
  public void onError(CometChatException e) {
      Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});

Unread Messages

Fetch unread messages by adding setUnread(true) to the builder. Use fetchPrevious() to retrieve them.
String UID = "cometchat-uid-1";

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder()
      .setUnread(true)
      .setLimit(20)
      .setUID(UID)
      .build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List<BaseMessage> list) {
      for (BaseMessage message : list) {
          if (message instanceof TextMessage) {
              Log.d(TAG, "Text message received successfully: " +((TextMessage) message).toString());
          } else if (message instanceof MediaMessage) {
              Log.d(TAG, "Media message received successfully: " +((MediaMessage) message).toString());
          }
      }
  }

  @Override
  public void onError(CometChatException e) {
      Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
The list of messages received is in the form of objects of BaseMessage class. A BaseMessage can either be an object of the TextMessage, MediaMessage, CustomMessage, Action or Call class. You can use the instanceOf operator to check the type of object.

Message History

Fetch the full conversation history using fetchPrevious(). Call it repeatedly on the same request object to paginate — useful for implementing upward scrolling.
private int limit = 30;
private String UID = "cometchat-uid-1"

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder()
      .setLimit(limit)
      .setUID(UID)
      .build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List<BaseMessage> list) {
      for (BaseMessage message : list) {
          if (message instanceof TextMessage) {
              Log.d(TAG, "Text message received successfully: " + ((TextMessage) message).toString());
          } else if (message instanceof MediaMessage) {
              Log.d(TAG, "Media message received successfully: " + ((MediaMessage)message).toString());
          }
      }
  }

  @Override
  public void onError(CometChatException e) {
      Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});

Search Messages

Add setSearchKeyword() to the builder to filter messages by keyword.
private int limit = 30;
private String UID = "cometchat-uid-1";

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setSearchKeyword("Hello").setUID(UID).setLimit(limit).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List<BaseMessage> list) {
      for (BaseMessage message : list) {
          if (message instanceof TextMessage) {
              Log.d(TAG, "Text message received successfully: " + ((TextMessage) message).toString());
          } else if (message instanceof MediaMessage) {
              Log.d(TAG, "Media message received successfully: " + ((MediaMessage)message).toString());
          }
      }
  }

  @Override
  public void onError(CometChatException e) {
      Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});

Search Capabilities

By default, search only matches message text. With Conversation & Advanced Search enabled, it also matches file names, mentions, and MIME types.
FeatureBasic SearchAdvanced Search
Text search
File name search
Mentions search
Mime type search
Conversation & Advanced Search is available on Advanced and Custom plans. Enable it from the CometChat Dashboard under Chats → Settings → General Configuration.

Unread Message Count

CometChat provides several methods to get unread counts at different scopes. All return results via a callback listener with a HashMap mapping IDs to counts. Each method accepts an optional boolean parameter to exclude messages from blocked users.
MethodScopeReturns
getUnreadMessageCountForUser(UID)Single user conversationHashMap<UID, count>
getUnreadMessageCountForGroup(GUID)Single group conversationHashMap<GUID, count>
getUnreadMessageCountForAllUsers()All user conversationsHashMap<UID, count>
getUnreadMessageCountForAllGroups()All group conversationsHashMap<GUID, count>
getUnreadMessageCount()EverythingHashMap<"user"/"group", HashMap>

Single Conversation

// One-on-one
private String UID = "cometchat-uid-1";

CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
  public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
      // handle success
  }

  @Override
  public void onError(CometChatException e) {
      // handle error
  }
});

// Group
private String GUID = "cometchat-guid-1";

CometChat.getUnreadMessageCountForGroup(GUID, new CometChat.CallbackListener<HashMap<String, Integer>>(){
  @Override
  public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
      // handle success
  }

  @Override
  public void onError(CometChatException e) {
      // handle error
  }
});

All Conversations

// All users and groups combined
CometChat.getUnreadMessageCount(new CometChat.CallbackListener<HashMap<String, HashMap<String, Integer>>>() {
  @Override
  public void onSuccess(HashMap<String, HashMap<String, Integer>> stringHashMapHashMap) {
      // handle success
  }

  @Override
  public void onError(CometChatException e) {
      // handle error
  }
});

// All user conversations only
CometChat.getUnreadMessageCountForAllUsers(new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
  public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
      // Handle Success
  }

  @Override
  public void onError(CometChatException e) {
      // Handle Error
  }
});

// All group conversations only
CometChat.getUnreadMessageCountForAllGroups(new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
  public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
      // Handle success
  }

  @Override
  public void onError(CometChatException e) {
      // Handle Error
  }
});

Excluding Blocked Users

Pass true as the second argument to any of the methods above to ignore messages from blocked users:
CometChat.getUnreadMessageCountForUser(UID, true, Callbacks);
CometChat.getUnreadMessageCountForGroup(GUID, true, Callbacks);
CometChat.getUnreadMessageCount(true, Callbacks);
CometChat.getUnreadMessageCountForAllUsers(true, Callbacks);
CometChat.getUnreadMessageCountForAllGroups(true, Callbacks);

Get Message Details

Use getMessageDetails() to fetch a specific message by its ID. Returns the full message object (TextMessage, MediaMessage, CustomMessage, or other BaseMessage subclass).
int messageId = MESSAGE_ID;

CometChat.getMessageDetails(messageId, new CometChat.CallbackListener<BaseMessage>() {
  @Override
  public void onSuccess(BaseMessage message) {
      Log.d(TAG, "Message details fetched: " + message.toString());
  }

  @Override
  public void onError(CometChatException e) {
      Log.d(TAG, "Error fetching message details: " + e.getMessage());
  }
});
ParameterTypeDescription
messageIdintThe ID of the message to fetch

Next Steps

Delivery & Read Receipts

Track when messages are delivered and read by recipients

Typing Indicators

Show real-time typing status in conversations

Message History

Advanced filtering options for message history

Send Message

Send text, media, and custom messages

Message Payload Structure

The BaseMessage object returned by SDK methods contains the following fields. TextMessage, MediaMessage, and CustomMessage extend this base structure with additional type-specific fields.
ParameterTypeDescription
idlongUnique message identifier
muidStringDeveloper-defined message ID for deduplication
senderUserUser who sent the message
receiverAppEntityMessage receiver (User or Group)
receiverUidStringReceiver’s unique identifier
typeStringMessage type. Values: "text", "image", "video", "audio", "file", "custom"
receiverTypeStringType of receiver. Values: "user", "group"
categoryStringMessage category. Values: "message", "action", "call", "custom"
sentAtlongUnix timestamp when message was sent
deliveredAtlongUnix timestamp when message was delivered
readAtlongUnix timestamp when message was read
metadataJSONObjectCustom message metadata set by developer
readByMeAtlongUnix timestamp when logged-in user read the message
deliveredToMeAtlongUnix timestamp when message was delivered to logged-in user
deletedAtlongUnix timestamp when message was deleted (0 if not deleted)
editedAtlongUnix timestamp when message was edited (0 if not edited)
deletedByStringUID of user who deleted the message (null if not deleted)
editedByStringUID of user who edited the message (null if not edited)
updatedAtlongUnix timestamp of last message update
conversationIdStringAssociated conversation identifier
parentMessageIdlongParent message ID for threaded messages (0 if not a reply)
replyCountintNumber of replies in thread
unreadRepliesCountintNumber of unread replies in thread
mentionedUsersArray<User>List of users mentioned in the message
hasMentionedMebooleanWhether the logged-in user is mentioned
reactionsArray<ReactionCount>List of reaction counts on the message
rawMessageJSONObjectRaw JSON message data
quotedMessageIdlongID of the quoted message (0 if not quoting)
quotedMessageBaseMessageThe quoted message object (null if not quoting)
Sample BaseMessage Object:
{
  "id": 12345,
  "muid": "msg_abc123",
  "sender": {
    "uid": "user_123",
    "name": "John Doe",
    "avatar": "https://example.com/avatar.png",
    "status": "online",
    "role": "default",
    "lastActiveAt": 1699900000
  },
  "receiver": {
    "uid": "user_456",
    "name": "Jane Smith",
    "avatar": "https://example.com/avatar2.png"
  },
  "receiverUid": "user_456",
  "type": "text",
  "receiverType": "user",
  "category": "message",
  "sentAt": 1699900000,
  "deliveredAt": 1699900001,
  "readAt": 1699900002,
  "metadata": {
    "priority": "high",
    "customField": "value"
  },
  "readByMeAt": 1699900002,
  "deliveredToMeAt": 1699900001,
  "deletedAt": 0,
  "editedAt": 0,
  "deletedBy": null,
  "editedBy": null,
  "updatedAt": 1699900000,
  "conversationId": "user_123_user_456",
  "parentMessageId": 0,
  "replyCount": 5,
  "unreadRepliesCount": 2,
  "mentionedUsers": [],
  "hasMentionedMe": false,
  "reactions": [
    {
      "reaction": "👍",
      "count": 3,
      "reactedByMe": true
    }
  ],
  "rawMessage": {},
  "quotedMessageId": 0,
  "quotedMessage": null
}
The nested User object (used in sender, receiver, mentionedUsers) contains:
ParameterTypeDescription
uidStringUnique identifier of the user
nameStringDisplay name of the user
avatarStringURL to user’s profile picture
linkStringURL to user’s profile page
roleStringUser role for access control
metadataJSONObjectCustom data set by developer
statusStringUser online status. Values: "online", "offline"
statusMessageStringCustom status message
lastActiveAtlongUnix timestamp of last activity
hasBlockedMebooleanWhether this user has blocked the logged-in user
blockedByMebooleanWhether the logged-in user has blocked this user
tagsArray<String>List of tags for user identification
deactivatedAtlongUnix timestamp when user was deactivated (0 if active)
The nested Group object (used in receiver for group messages) contains:
ParameterTypeDescription
guidStringUnique identifier of the group
nameStringDisplay name of the group
typeStringGroup type. Values: "public", "private", "password"
iconStringURL to group icon
descriptionStringGroup description
ownerStringUID of group owner
metadataJSONObjectCustom data set by developer
membersCountintNumber of group members
tagsArray<String>List of tags for group identification
hasJoinedbooleanWhether logged-in user has joined
scopeStringUser’s scope in group. Values: "admin", "moderator", "participant"
The nested ReactionCount object (used in reactions array) contains:
ParameterTypeDescription
reactionStringThe reaction emoji
countintTotal count of this reaction
reactedByMebooleanWhether the logged-in user has reacted with this emoji