Retrieve Historical Messages
Historical messages can be retrieved from local storage only, remote storage only, or both local and remote storage.
Enable Service
Retrieving one-to-one and group chat historical messages from remote storage refers to obtaining historical messages from RC's server. The Cloud Storage for One-to-One and Group Messages service is enabled by default. You can retrieve historical messages directly. If using a production environment App Key, this service is available for Chat Starter Plan or Chat Pro Plan. For specific features and pricing, refer to the RC Official Pricing Page.
Note: Please distinguish between historical message records and offline messages?. RC provides offline message caching for one-to-one chats, group chats, and system messages by default, with a maximum duration of 7 days (adjustable). The SDK automatically retrieves messages received during offline periods when the client comes online, with no need for API calls at the application layer. See Manage Offline Message Storage Configuration for details.
Retrieve Messages from Local Database
Use the getHistoryMessages method to paginate through historical messages stored in the local database for a specified conversation, returning a list of message objects. Messages in the list are ordered from newest to oldest by send time.
Retrieve All Message Types in a Conversation
RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, oldestMessageId, count,callback);
The count parameter specifies how many messages should be included in the returned list. The oldestMessageId parameter controls pagination boundaries. Each time the getHistoryMessages method is called, the SDK uses the message pointed to by the oldestMessageId parameter as the boundary to return the specified number of messages on the next page. To retrieve the latest count messages in the conversation, set oldestMessageId to -1.
It is recommended to obtain the ID of the earliest message in the returned results and use it as the oldestMessageId in the next call to traverse the entire conversation's message history.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type |
| targetId | String | Conversation ID |
| oldestMessageId | long | ID of the last message. Set to -1 to query the latest messages in the local database. |
| count | int | Number of messages per page. |
| callback | ResultCallback<List<Message>> | Callback for retrieving historical messages, ordered from newest to oldest. |
Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
String targetId = "Conversation Id";
int oldestMessageId = -1;
int count = 10;
RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, oldestMessageId, count,
new RongIMClient.ResultCallback<List<Message>>() {
/**
* Success callback
* @param messages Retrieved message list
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Error callback.
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Retrieve Messages of Specified Types in a Conversation
RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, objectName, oldestMessageId, count, callback);
The count parameter specifies how many messages should be included in the returned list. The oldestMessageId parameter controls pagination boundaries. Each time the getHistoryMessages method is called, the SDK uses the message pointed to by the oldestMessageId parameter as the boundary to return the specified number of messages on the next page. To retrieve the latest count messages in the conversation, set oldestMessageId to -1. The objectName parameter specifies the message type to retrieve.
It is recommended to obtain the ID of the earliest message in the returned results and use it as the oldestMessageId in the next call to traverse the entire conversation's message history.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type. |
| targetId | String | Conversation ID. |
| objectName | String | Message type identifier. For built-in message type identifiers, see [Message Type Overview]. |
| oldestMessageId | long | ID of the last message. Set to -1 to query the latest messages in the local database. |
| count | int | Number of messages per page. |
| callback | ResultCallback<List<Message>> | Callback for retrieving historical messages, ordered from newest to oldest. |
Retrieve Messages by Message UID
- Starting from SDK version 5.2.5.2, batch message retrieval by UID is supported. This is only available in the ChannelClient class. Supported conversation types include one-to-one chat, group chat, chatroom, and ultra group.
- For SDK versions below 5.2.5.2, use the
getMessageByUIdmethod in the RongCoreClient class, which supports only one UID per call.
A message's UID is a globally unique ID generated by RC's server. After messages are stored in the local database, an app may need to retrieve specific messages again. For example, if your users want to bookmark certain messages from their chat history, the app can first record the messages' UIDs and then call getBatchLocalMessages when needed to display them, passing the bookmarked message UIDs to retrieve the messages from the local database.
ChannelClient.getInstance().getBatchLocalMessages(conversationType, targetId, channelId, messageUIDs, callback);
As long as you have the message UIDs (messageUIDs) and the messages are stored in the local database, you can use this method to retrieve messages from the local database. Each call can only retrieve messages from one conversation (targetId) or ultra group channel (channelId).
For ultra groups or chatrooms, please note the following:
-
Ultra group conversations only synchronize the last message by default. If you directly call this method (e.g., passing UIDs obtained through RC server callbacks like Post-messaging Callback), the SDK may fail to locate corresponding messages locally. We recommend first calling
getBatchRemoteUltraGroupMessagesto fetch messages from the server. -
Chatroom messages are automatically cleared from local storage when users exit. If users call this interface after leaving the chatroom, local messages cannot be retrieved.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type, supporting one-to-one, group, chatroom, and ultra group. |
| targetId | String | Conversation ID |
| channelId | String | Ultra group channel ID. Pass empty string "" for non-ultra group types. |
| messageUIDs | List<String> | Message UIDs (globally unique IDs generated by RC server). Max 20 valid UIDs supported. |
| callback | IRongCoreCallback.IGetMessagesByUIDsCallback | Callback for retrieving messages. Returns message list and failed UIDs. |
Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
String targetId = "conversationId";
String sampleMessageUID = "C3GC-8VAA-LJQ4-TPPM";
List<String> messageUIDs = new ArrayList<>();
messageUIDs.add(sampleMessageUID);
ChannelClient.getInstance().getBatchLocalMessages(conversationType, targetId, null, messageUIDs,
new IRongCoreCallback.IGetMessagesByUIDsCallback() {
/**
* Success callback
* @param messages Retrieved message list
* @param mismatchList List of failed message UIDs
*/
@Override
public void onSuccess(List<Message> messages, List<String> mismatchList) {
}
/**
* Error callback
* @param errorCode Error code
*/
@Override
public void onError(IRongCoreEnum.CoreErrorCode errorCode) {
}
});
Retrieve Remote History Messages
Use getRemoteHistoryMessages to directly query historical messages stored in Cloud Storage for One-to-One and Group Messages.
-
Whether users can access group messages sent before joining depends on App settings in Console. Enable Retrieve group history when not in group in the RC Console under Chat > Chat settings > One-to-One and Group Chats > Retrieve group history when not in group to allow new members to view all historical messages. Otherwise, they only see messages sent after joining.
-
By default, users cannot retrieve group history when not in the group. To override this, enable Retrieve group history when not in group in RC Console under Chat > Chat settings > One-to-One and Group Chats.
Retrieve Conversation's Remote History
The SDK queries Cloud Storage for One-to-One and Group Messages and returns deduplicated messages sorted newest-to-oldest.
Since this interface deduplicates against local messages by default, we recommend using getHistoryMessages first to exhaust local messages before fetching remote history. Otherwise, some/all target messages might be missed.
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, dateTime, count,callback);
The count parameter specifies the number of messages to return. The dateTime parameter controls pagination boundaries. Each call returns the next page of messages older than dateTime. Pass 0 to fetch the latest count messages.
For pagination, use the sentTime of the oldest returned message as the next dateTime value.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type |
| targetId | String | Conversation ID |
| dateTime | long | Timestamp threshold. Messages older than dateTime are returned. 0 fetches latest count messages. |
| count | int | Message count. Range [2-20] for SDK <5.4.1; [2-100] for SDK ≥5.4.1. |
| callback | ResultCallback<List<Message>> | Callback returning messages sorted newest-to-oldest. |
Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
String targetId = "conversationId";
long dateTime = 0;
int count = 20;
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, dateTime, count,
new RongIMClient.ResultCallback<List<Message>>() {
/**
* Success callback
* @param messages Retrieved message list
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Error callback
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Custom Remote History Retrieval
Use RemoteHistoryMsgOption to customize getRemoteHistoryMessages behavior for querying Cloud Storage for One-to-One and Group Messages.
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, remoteHistoryMsgOption, callback);
The remoteHistoryMsgOption contains multiple configuration items. The count and dateTime parameters specify the number of historical messages to retrieve and the pagination timestamp respectively. The pullOrder parameter controls the chronological direction for retrieving messages, allowing selection of messages either earlier or later than the given dateTime. The includeLocalExistMessage parameter determines whether the returned message list should include messages already present in the local database.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type |
| targetId | String | Conversation ID |
| remoteHistoryMsgOption | RemoteHistoryMsgOption | Remote history retrieval configuration options |
| callback | ResultCallback<List<Message>> | Callback for retrieving messages |
-
RemoteHistoryMsgOptionDetails:Parameter Description dataTime Timestamp for pagination boundary control. Default value: 0count Number of messages to retrieve. For SDK versions < 5.4.1, range is [2-20]; for SDK versions ≥ 5.4.1, range is [2-100]; default value: 5pullOrder Retrieval order. DESCEND: Descending order - retrieves messages sent beforedataTimein reverse chronological order (newest to oldest).ASCEND: Ascending order - retrieves messages sent afterdataTimein chronological order (oldest to newest). Default:1includeLocalExistMessage Whether to include messages already in local database. true: Include - returns results without deduplication.false: Exclude - deduplicates against local database before returning. Default:false
By default, RemoteHistoryMsgOption queries messages in descending chronological order and performs deduplication against the local database before returning results. When includeLocalExistMessage is set to false, it's recommended that apps first use getHistoryMessages to retrieve all local messages before fetching remote history, otherwise some or all specified messages might be missed.
For ascending chronological queries, it's recommended to use the sentTime of the newest message in the returned results as the dateTime value for subsequent calls, enabling traversal through the entire conversation history. Ascending queries are typically used when jumping to a specific message position in the conversation UI and needing to retrieve newer historical messages.
Conversation.ConversationType conversationType= Conversation.ConversationType.PRIVATE;
String targetId="Conversation ID";
RemoteHistoryMsgOption remoteHistoryMsgOption=new RemoteHistoryMsgOption();
remoteHistoryMsgOption.setDataTime(1662542712112L);//2022-09-07 17:25:12:112
remoteHistoryMsgOption.setOrder(HistoryMessageOption.PullOrder.DESCEND);
remoteHistoryMsgOption.setCount(20);
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, remoteHistoryMsgOption,
new RongIMClient.ResultCallback<List<Message>>() {
/**
* Success callback
* @param messages Retrieved message list
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Error callback.
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Retrieving Local and Remote History Messages
This interface is provided by RongCoreClient. Note: Whether users can access group chat history before joining depends on App settings in the Console. You can enable Allow New Members to Access Pre-Join History in the [Feature Configuration] page. When enabled, new members can view all group messages sent before they joined. When disabled, new members only see messages sent after joining.
The difference between getMessages and getRemoteHistoryMessages is that getMessages first queries the local database for messages in the specified conversation. When local messages don't meet the query conditions, it then queries Cloud Storage for One-to-One and Group Messages to return a continuous and adjacent list of message objects.
RongCoreClient.getInstance().getMessages(conversationType, targetId, historyMessageOption, callback);
The historyMessageOption controls the behavior of getMessages. The count parameter specifies how many messages should be included in the returned list. The dateTime parameter controls pagination boundaries. For each call to getRemoteHistoryMessages, the SDK uses dateTime as a boundary to return the specified number of messages from the next page. To retrieve the latest count messages in a conversation, set dateTime to 0. The pullOrder parameter controls the chronological direction for retrieving messages, allowing selection of messages either earlier or later than the given dateTime.
It's recommended to use the sentTime of the oldest message in the returned results as the dateTime value for subsequent calls, enabling traversal through the entire conversation history.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [ConversationType] | Conversation type |
| targetId | String | Conversation ID |
| historyMsgOption | HistoryMessageOption | History retrieval configuration options |
| callback | IRongCoreCallback.IGetMessageCallback<List<Message>> | Callback for retrieving messages |
HistoryMessageOptionDetails:
| Parameter | Description |
|---|---|
| dataTime | Timestamp used to control the boundary for paginated message queries. Default value is 0. |
| count | Number of messages to retrieve. For SDK versions < 5.4.1, range is [2-20]; for SDK versions ≥ 5.4.1, range is [2-100]; default value is 5. |
| pullOrder | Retrieval order. DESCEND: Descending order - retrieves messages sent before dataTime in reverse chronological order, returning messages from newest to oldest. ASCEND: Ascending order - retrieves messages sent after dataTime in chronological order, returning messages from oldest to newest. |
By default, HistoryMessageOption queries messages in ascending order by sent time. Ascending order queries are typically used when jumping to a specific message position in the chat UI and needing to query newer historical messages.
For descending order queries by message sent time, it's recommended to obtain the sentTime of the earliest message in the returned results and use it as the dateTime value in subsequent calls to traverse the entire conversation message history.
Conversation.ConversationType conversationType= Conversation.ConversationType.PRIVATE;
String targetId="Conversation Id";
HistoryMessageOption historyMessageOption=new HistoryMessageOption();
historyMessageOption.setDataTime(1662542712112L);//2022-09-07 17:25:12:112
historyMessageOption.setOrder(HistoryMessageOption.PullOrder.ASCEND);
historyMessageOption.setCount(20);
RongCoreClient.getInstance().getMessages(conversationType, targetId, historyMessageOption, new IRongCoreCallback.IGetMessageCallback() {
@Override
public void onComplete(List<Message> list, IRongCoreEnum.CoreErrorCode coreErrorCode) {
Log.e("tag","list---"+list.size());
}
});