Retrieve Historical Messages
Historical messages can be retrieved from local data only, from the remote server only, or from both local and remote sources.
Enable Service
Retrieving historical messages for one-to-one and group chats from the remote server requires that the Cloud Storage for One-to-One and Group Messages service provided by RC is enabled for your App Key. You can enable this service for the currently used App Key on the Chat pricing plans page in the Console. If you are using a production environment App Key, note that only the Chat Premium Plan or Chat Ultimate Plan can enable this service. For specific features and pricing, refer to the Billing Instructions document.
Note: Please distinguish between historical message records and offline messages?. RC provides up to 7 days (adjustable) of offline message caching for one-to-one chats, group chats, and system messages by default. The SDK automatically retrieves messages during the offline period when the client comes online, without requiring an API call at the App level. For more details, see Manage Offline Message Storage Configuration.
Retrieve Messages from Local Database
Use the getHistoryMessages
method to paginate and retrieve historical messages stored in the local database for a specified conversation, returning a list of message objects. The messages in the list are ordered from newest to oldest.
Retrieve All Types of Messages in a Conversation
RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, oldestMessageId, count,callback);
The count
parameter specifies the number of messages to include in the returned list. The oldestMessageId
parameter controls the pagination boundary. Each time the getHistoryMessages
method is called, the SDK will use the message pointed to by the oldestMessageId
parameter as the boundary and continue 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 retrieve the ID of the earliest message in the returned result and use it as the oldestMessageId
in the next call to traverse the entire conversation 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>>() {
/**
* Callback for success
* @param messages List of retrieved messages
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Callback for error
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Retrieve Messages of a Specified Type in a Conversation
RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, objectName, oldestMessageId, count, callback);
The count
parameter specifies the number of messages to include in the returned list. The oldestMessageId
parameter controls the pagination boundary. Each time the getHistoryMessages
method is called, the SDK will use the message pointed to by the oldestMessageId
parameter as the boundary and continue 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 type of messages to retrieve.
It is recommended to retrieve the ID of the earliest message in the returned result and use it as the oldestMessageId
in the next call to traverse the entire conversation 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, the interface for retrieving messages in bulk by UID is supported. It is only available in the ChannelClient class. Supported conversation types include one-to-one chat, group chat, chatroom, and ultra group.
- If the SDK version is lower than 5.2.5.2, you can use the
getMessageByUId
method in the RongCoreClient class, which supports only one UID per call.
The message UID is a globally unique ID generated by the RC server. After a message is stored in the local database, the App may need to extract specific messages again. For example, if your users want to bookmark some messages in the chat history, the App can first record the message UID and then call getBatchLocalMessages
, passing the bookmarked message UIDs to extract the messages from the local database.
ChannelClient.getInstance().getBatchLocalMessages(conversationType, targetId, channelId, messageUIDs, callback);
As long as the message UIDs (messageUIDs
) are held and the messages are stored in the local database, this method can be used to extract messages from the local database. Only messages from one conversation (targetId
) or ultra group channel (channelId
) can be extracted at a time.
For ultra group or chatroom conversation types, please note the following:
- Ultra group conversations only synchronize the last message by default. If you directly call this method (e.g., you pass UIDs obtained via the RC server callback Post-messaging Callback), the SDK may not find the corresponding messages locally. It is recommended to first call
getBatchRemoteUltraGroupMessages
to retrieve messages from the server. - Chatroom conversations automatically clear local messages when the user exits. If the user exits the chatroom and then calls this interface, local messages cannot be retrieved.
Parameter | Type | Description |
---|---|---|
conversationType | [ConversationType] | Conversation type, supporting one-to-one chat, group chat, chatroom, and ultra group. |
targetId | String | Conversation ID |
channelId | String | Channel ID for ultra group. Pass null for non-ultra group conversation types. |
messageUIDs | List<String> | Message UIDs, which are globally unique IDs generated by the RC server. Valid UIDs must be passed, with a maximum of 20. |
callback | IRongCoreCallback.IGetMessagesByUIDsCallback | Callback for retrieving historical messages. On success, returns a list of messages and a list of UIDs for messages that failed to be retrieved. |
Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
String targetId = "Conversation Id";
String sampleMessageUID = "C3GC-8VAA-LJQ4-TPPM";
List<String> messageUIDs = new ArrayList<>();
messageUIDs.add(sampleMessageUID);
ChannelClient.getInstance().getBatchLocalMessages(conversationType, targetId, null, messageUIDs,
new IRongCoreCallback.IGetMessagesByUIDsCallback() {
/**
* Callback for success
* @param messageList List of retrieved messages
* @param mismatchList List of UIDs for messages that failed to be retrieved
*/
@Override
public void onSuccess(List<Message> messages, List<String> mismatchList) {
}
/**
* Callback for error
* @param errorCode Error code
*/
@Override
public void onError(IRongCoreEnum.CoreErrorCode errorCode) {
}
});
Retrieve Remote Historical Messages
Use the getRemoteHistoryMessages
method to directly query historical messages stored in the Cloud Storage for One-to-One and Group Messages for a specified conversation.
- Whether users can retrieve historical messages sent before they joined a group depends on the App's settings in the Console. You can enable Allow New Users to Retrieve Historical Messages Sent Before Joining on the Basic Features page in the Console. When this option is enabled, new group members can retrieve all group messages sent before they joined. If not enabled, new group members can only see group messages sent after they joined.
- By default, users who are not in a group cannot retrieve historical messages from that group. If you want users who are not in a specified group to also retrieve historical messages from that group, you can allow this by navigating to Configuration > Chat settings > Basic features > One-to-One and Group Chat > Allow Users Not in Group to Retrieve Historical Messages in the RC Console.
Retrieve Remote Historical Messages for a Conversation
The SDK directly queries and retrieves historical messages from the Cloud Storage for One-to-One and Group Messages that meet the query conditions. The query results are compared with the local database to exclude duplicate messages, and a list of message objects is returned. The messages in the returned list are ordered from newest to oldest.
Since this interface returns messages after deduplication with local messages by default, it is recommended to first use getHistoryMessages
to retrieve all messages from the local database before retrieving remote historical messages. Otherwise, some or all of the specified messages may not be retrieved.
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, dateTime, count,callback);
The count
parameter specifies the number of messages to include in the returned list. The dateTime
parameter controls the pagination boundary. Each time the getRemoteHistoryMessages
method is called, the SDK will use dateTime
as the boundary and continue to return the specified number of messages on the next page. To retrieve the latest count
messages in the conversation, set dateTime
to 0.
It is recommended to retrieve the sentTime
of the earliest message in the returned result and use it as the dateTime
value in the next call to traverse the entire conversation history.
Parameter | Type | Description |
---|---|---|
conversationType | [ConversationType] | Conversation type |
targetId | String | Conversation ID |
dateTime | long | Timestamp, retrieving historical messages sent before dateTime . Pass 0 to retrieve the latest count messages. |
count | int | Number of messages to retrieve. If SDK < 5.4.1, range is [2-20]; if SDK ≧ 5.4.1, range is [2-100]. |
callback | ResultCallback<List<Message>> | Callback for retrieving historical messages, ordered from newest to oldest. |
Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
String targetId = "Conversation Id";
long dateTime = 0;
int count = 20;
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, dateTime, count,
new RongIMClient.ResultCallback<List<Message>>() {
/**
* Callback for success
* @param messages List of retrieved messages
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Callback for error
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Customize Retrieval of Remote Historical Messages
Use RemoteHistoryMsgOption
to customize the behavior of the getRemoteHistoryMessages
method for retrieving remote historical messages. The SDK will directly query the Cloud Storage for One-to-One and Group Messages for historical messages that meet the query conditions.
RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, remoteHistoryMsgOption, callback);
remoteHistoryMsgOption
contains multiple configuration items, where count
and dateTime
parameters specify the number of historical messages to retrieve and the pagination query timestamp, respectively. The pullOrder
parameter controls the time direction for retrieving historical messages, allowing retrieval of messages either earlier or later than the given dateTime
. The includeLocalExistMessage
parameter controls whether the returned message list should include messages that already exist in the local database.
Parameter | Type | Description |
---|---|---|
conversationType | [ConversationType] | Conversation type |
targetId | String | Conversation ID |
remoteHistoryMsgOption | RemoteHistoryMsgOption | Configuration options for retrieving remote historical messages. |
callback | ResultCallback<List<Message>> | Callback for retrieving historical messages. |
-
RemoteHistoryMsgOption
Description:Parameter Description dataTime Timestamp, used to control the boundary for paginated message queries. Default is 0
.count Number of messages to retrieve. If SDK < 5.4.1, range is [2-20]; if SDK ≧ 5.4.1, range is [2-100]; default is 5
.pullOrder Pull order. DESCEND
: Descending order, retrieves messages sent beforedataTime
in descending order of send time, returning messages in the list from newest to oldest.ASCEND
: Ascending order, retrieves messages sent afterdataTime
in ascending order of send time, returning messages in the list from oldest to newest. Default is1
.includeLocalExistMessage Whether to include messages that already exist in the local database. true
: Include, query results are returned directly without deduplication with the local database.false
: Exclude, query results are deduplicated with the local database, returning only messages that do not exist in the local database. Default isfalse
.
By default, RemoteHistoryMsgOption
queries messages in a conversation in descending order of send time, and the query results are deduplicated with the local database before returning the message objects. When includeLocalExistMessage
is set to false
, it is recommended to first use getHistoryMessages
to retrieve all messages from the local database before retrieving remote historical messages, otherwise some or all of the specified messages may not be retrieved.
To query messages in a conversation in ascending order of send time, it is recommended to retrieve the sentTime
of the latest message in the returned result and use it as the dateTime
value in the next call to traverse the entire conversation history. Ascending order queries are generally used for scenarios where you need to query newer historical messages after jumping to a specific message position in the conversation.
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>>() {
/**
* Callback for success
* @param messages List of retrieved messages
*/
@Override
public void onSuccess(List<Message> messages) {
}
/**
* Callback for error
* @param e Error code
*/
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
Retrieve Local and Remote Historical Messages
This interface is provided in the RongCoreClient class. Note: Whether users can retrieve historical messages sent before they joined a group depends on the App's settings in the Console. You can enable Allow New Users to Retrieve Historical Messages Sent Before Joining on the Basic Features page in the Console. When this option is enabled, new