Skip to main content

Retrieving Historical Messages

When retrieving historical messages, you can choose to fetch them from local storage only, from the remote server only, or simultaneously from both local and remote sources. Ultra group conversations do not have offline messages. To retrieve messages received while the user was offline, you need to fetch remote historical messages based on the last message in the ultra group conversation.

  • If your application/environment enabled ultra group services on or after October 13, 2022, the ultra group service includes a default channel with ID RCDefault. When sending messages without specifying a channel ID, the messages will be sent to the RCDefault channel. To retrieve historical messages from the RCDefault channel, you must pass this channel ID.
  • If your application/environment enabled ultra group services before October 13, 2022, messages sent without specifying a channel ID will not belong to any channel. When retrieving historical messages without passing a channel ID, you can retrieve messages that don't belong to any channel. RC supports adjusting services to the latest behavior for customers. This behavior adjustment will affect multiple functions including message sending/receiving, conversation retrieval, history clearing, and muting across both client and server. If needed, please submit a ticket to consult about detailed solutions.

Retrieving Local and Remote Historical Messages

You can use the getMessages method to first retrieve historical messages from local storage. If there are missing messages locally, the system will synchronize the missing portions from the server. When no more messages are available locally, they will be pulled from the server.

Interface

interface IGetMessageCallbackEx{
void onComplete(List<Message> messageList, long syncTimestamp, boolean hasMoreMsg, IRongCoreEnum.CoreErrorCode errorCode);
void onFail(IRongCoreEnum.CoreErrorCode errorCode);
}

public void getMessages(final Conversation.ConversationType conversationType, final String targetId, final String channelId, final HistoryMessageOption historyMessageOption, final IRongCoreCallback.IGetMessageCallbackEx callback)

Parameter Description

ParameterTypeDescription
conversationTypeConversationTypeConversation type
targetIdStringConversation ID
channelStringUltra group channel ID
historyMsgOptionHistoryMessageOptionConfiguration options for retrieving historical messages.
callbackIRongCoreCallback.IGetMessageCallback<List<Message>>Callback for retrieving historical messages.
  • HistoryMessageOption Description:

    ParameterDescription
    dataTimeTimestamp used to control the boundary for paginated message queries. Default value is 0.
    countNumber of messages to retrieve. For SDK versions < 5.4.1, the range is [2-20]; for SDK versions ≥ 5.4.1, the range is [2-100]; default value is 5.
    pullOrderRetrieval order. DESCEND: Descending order, retrieves messages with timestamps earlier than dataTime in descending order of sending time, returning messages from newest to oldest. ASCEND: Ascending order, retrieves messages with timestamps later than dataTime in ascending order of sending time, returning messages from oldest to newest.

Retrieving Messages from Local Database

You can use the getHistoryMessages method to paginate and query historical messages stored in the local database for a specified conversation, obtaining an asynchronously returned list of message objects. The messages in the list are arranged in descending order of sending time (newest to oldest).

Retrieving Messages Before a Specified messageId

Asynchronously retrieves the specified number of latest message entities before a given message in a conversation, returning a list of Message objects.

Interface

public abstract void getHistoryMessages(
final Conversation.ConversationType conversationType,
final String targetId,
final int oldestMessageId,
final int count,
final String channelId,
final IRongCoreCallback.ResultCallback<List<Message>> callback);

Parameter Description

The count parameter specifies how many messages should be included in the returned list. The oldestMessageId parameter controls the pagination boundary. Each time the getHistoryMessages method is called, the SDK uses the message pointed to by the oldestMessageId parameter as the boundary and continues 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.

ParameterTypeDescription
conversationTypeConversationTypeConversation type.
targetIdStringConversation ID.
oldestMessageIdlongID of the last message. Set to -1 to query the latest messages in the local database.
countintNumber of messages per page.
channelIdStringUltra group channel ID.
callbackResultCallback<List<Message>>Callback for retrieving historical messages, arranged in descending order of time (newest to oldest).

Retrieving Messages Around a Specified Timestamp

tip

Ultra group services support this feature starting from version 5.4.5.

Retrieves the specified number of latest message entities before and after a given timestamp in a conversation, returning a list of Message objects.

Interface

public abstract void getHistoryMessages(
final Conversation.ConversationType conversationType,
final String targetId,
final String channelId,
final long sentTime,
final int before,
final int after,
final IRongCoreCallback.ResultCallback<List<Message>> resultCallback);

Parameter Description

ParameterTypeDescription
conversationTypeConversationTypeConversation type.
targetIdStringConversation ID.
channelIdStringUltra group channel ID.
timestamplongTimestamp boundary for retrieving historical messages (earlier or later than this timestamp).
beforeintNumber of messages to retrieve that were sent before the specified timestamp.
afterintNumber of messages to retrieve that were sent after the specified timestamp.
callbackResultCallback<List<Message>>Callback for retrieving historical messages, sorted chronologically from newest to oldest.

Retrieve Messages of Specified Types in a Conversation

The following method asynchronously returns a list of Message objects containing the latest messages of specific types before the specified message.

Interface

public abstract void getHistoryMessages(
final Conversation.ConversationType conversationType,
final String targetId,
final String channelId,
final String objectName,
final int oldestMessageId,
final int count,
final IRongCoreCallback.ResultCallback<List<Message>> callback);

Parameter Description

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 a 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 history.

ParameterTypeDescription
conversationTypeConversationTypeConversation type.
targetIdStringConversation ID.
objectNameStringMessage type identifier. Built-in message type identifiers can be found in Message Type Overview.
oldestMessageIdlongID of the last message. Set to -1 to query the latest messages in the local database.
countintNumber of messages per page.
channelIdStringUltra group channel ID.
callbackResultCallback<List<Message>>Callback for retrieving historical messages, sorted chronologically from newest to oldest.

To retrieve historical messages before or after a specified message, you can use the following method with the direction parameter:

Interface

public abstract void getHistoryMessages(
final Conversation.ConversationType conversationType,
final String targetId,
final String channelId,
final String objectName,
final int baseMessageId,
final int count,
final RongCommonDefine.GetMessageDirection direction,
final IRongCoreCallback.ResultCallback<List<Message>> callback);

Parameter Description

ParameterTypeDescription
conversationTypeConversationTypeConversation type.
targetIdStringConversation ID.
channelIdStringUltra group channel ID.
objectNameStringMessage type identifier. Built-in message type identifiers can be found in Message Type Overview.
baseMessageIdintMessage ID boundary for retrieving historical messages (before or after this message).
countintNumber of messages per page.
channelIdStringUltra group channel ID.
directionRongCommonDefine.GetMessageDirectionFRONT retrieves messages before the specified timestamp. BEHIND retrieves messages after the specified timestamp.
callbackResultCallback<List<Message>>Callback for retrieving historical messages, sorted chronologically from newest to oldest.

Retrieve Historical Messages of Multiple Specified Types

Retrieves a list of Message objects containing the latest messages of multiple specified types before or after a specified message in a conversation.

Interface

public abstract void getHistoryMessages(
final Conversation.ConversationType conversationType,
final String targetId,
final String channelId,
final List<String> objectNames,
final long timestamp,
final int count,
final RongCommonDefine.GetMessageDirection direction,
final IRongCoreCallback.ResultCallback<List<Message>> callback);

Parameter Description

ParameterTypeDescription
conversationTypeConversationTypeConversation type.
targetIdStringConversation ID.
channelIdStringUltra group channel ID.
objectNamesList<String>Message type identifiers. Built-in message type identifiers can be found in Message Type Overview.
timestamplongUses this timestamp as a boundary to retrieve historical messages before or after this time.
countintNumber of messages per page.
directionRongCommonDefine.GetMessageDirectionFRONT means retrieving messages before the passed timestamp. BEHIND means retrieving messages after the passed timestamp.
callbackResultCallback<List<Message>>Callback for retrieving historical messages, sorted chronologically from newest to oldest.

Ultra groups also support extracting messages from the local database using message UIDs. For details, see Retrieve Messages by Message UID in Retrieve Historical Messages.

Retrieve Remote Historical Messages

Starting from version 5.6.4, the IMLib SDK supports using the getRemoteHistoryMessages method of ChannelClient to directly query historical messages stored in Cloud Storage for Ultra Group Messages for a specified conversation.

tip

Whether users can retrieve group chat historical messages from before they joined the ultra group depends on the App's settings in the Console. By default, new group members can only see group chat messages sent after they joined.

Retrieve Remote Historical Messages for a Conversation

You can customize the behavior of the getRemoteHistoryMessages method using RemoteHistoryMsgOption to retrieve remote historical messages. The IMLib SDK will directly query historical messages that meet the specified conditions from Cloud Storage for One-to-One and Group Messages.

Parameter Description

ParameterTypeDescription
conversationTypeConversationTypeConversation type
channelIdStringChannel ID
targetIdStringConversation ID
remoteHistoryMsgOptionRemoteHistoryMsgOptionConfiguration options for retrieving remote historical messages.
callbackResultCallback<List<Message>>Callback for retrieving historical messages.
  • RemoteHistoryMsgOption Description:

    ParameterDescription
    dataTimeTimestamp used to control the boundary for paginated message queries. Default value is 0.
    countNumber of messages to retrieve. For SDK versions < 5.4.1, the range is [2-20]; for SDK versions ≧ 5.4.1, the range is [2-100]; default value is 5.
    pullOrderRetrieval order. DESCEND: Descending order, retrieves messages sent before dataTime in chronological order from newest to oldest, with the returned list sorted from newest to oldest. ASCEND: Ascending order, retrieves messages sent after dataTime in chronological order from oldest to newest, with the returned list sorted from oldest to newest. Default value is 1.
    includeLocalExistMessageWhether to include messages already present in the local database. true: Includes them, returning the query results directly without deduplication against the local database. false: Excludes them, deduplicating the query results against the local database and returning only messages not present locally. Default value is false.

By default, RemoteHistoryMsgOption queries messages in a conversation in descending order of their sent time and compares the query results with the local database to exclude duplicate messages before returning the message object list. When includeLocalExistMessage is set to false, it is recommended that the App layer first uses getHistoryMessages to retrieve all messages from the local database before fetching remote historical messages; otherwise, some or all specified messages may not be retrieved.

To query messages in ascending order of their sent time, it is recommended to use the sentTime of the newest message in the returned results as the dateTime value for the next call, enabling traversal of the entire conversation's message history. Ascending order queries are generally useful for scenarios where you need to query newer historical messages after jumping to a specific message position in the conversation UI.

Example Code

Conversation.ConversationType conversationType= Conversation.ConversationType.ULTRA_GROUP;
String targetId="Conversation Id";
String channelId="Channel Id";
RemoteHistoryMsgOption remoteHistoryMsgOption=new RemoteHistoryMsgOption();
remoteHistoryMsgOption.setDataTime(1662542712112L);//2022-09-07 17:25:12:112
remoteHistoryMsgOption.setOrder(HistoryMessageOption.PullOrder.DESCEND);
remoteHistoryMsgOption.setCount(20);

ChannelClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, remoteHistoryMsgOption,
new IRongCoreCallback.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(IRongCoreEnum.CoreErrorCode e) {

}
});

Force Retrieval of Specific Batches of Messages from the Server

You can use the getBatchRemoteUltraGroupMessages interface to forcibly retrieve corresponding messages from the server. Upon successful retrieval, it will forcibly update local messages.

Interface

matchedMsgList List of messages retrieved from the server
notMatchMsgList Invalid parameters or messages not found on the server

interface IGetBatchRemoteUltraGroupMessageCallback {
void onSuccess(List<Message> matchedMsgList, List<Message> notMatchedMsgList);

void onError(IRongCoreEnum.CoreErrorCode errorCode);
}

public void getBatchRemoteUltraGroupMessages(final List<Message> msgList,final IRongCoreCallback.IGetBatchRemoteUltraGroupMessageCallback callback)

Parameter Description

ParameterTypeDescription
messagesList<Message>Message list. Maximum of 20 messages can be queried. All messages must be of ultra group type and belong to the same conversation. Each message object must contain valid values for ConversationType, targetId, channelId, messageUid, and sentTime.
callbackIGetBatchRemoteUltraGroupMessageCallbackCallback for failed message count queries.

Count Local Historical Messages

tip

ChannelClient This capability is supported starting from version 5.6.4.

You can obtain the count of messages within a specified time range for a given ultra group. This method supports passing a list of channels. If no channels are specified, it returns the count of historical messages for all channels locally.

Interface

public abstract void getUltraGroupMessageCountByTimeRange(
String targetId,
String[] channelIds,
long startTime,
long endTime,
IRongCoreCallback.ResultCallback<Integer> callback);

Parameter Description

ParameterTypeDescription
targetIdStringUltra group conversation targetId
channelIdsString[]List of ultra group channel channelIds
sentTimelongQuery messages after startTime, where startTime >= 0.
endTimelongQuery messages before endTime, where endTime > startTime.
callbackResultCallback <Integer>Interface callback