历史消息

更新时间: 2025/08/27 17:17:19

网易云信 IM 支持对客户端本地和网易云信服务器存储历史消息进行查询、删除操作。

本文介绍如何调用 NIM SDK 的接口实现历史消息管理。

支持平台

本文内容适用的开发平台或框架如下表所示,涉及的接口请参考下文 相关接口 章节:

安卓 iOS macOS/Windows Web/uni-app/小程序 Node.js/Electron 鸿蒙 Flutter
✔️️️️ ✔️️️️ ✔️️️️ ✔️️️️ ✔️️️️ ✔️️️️ ✔️️️️

准备工作

使用该功能前,请在 网易云信控制台 开通 历史消息 功能,具体请参考 配置基础功能/全局功能

网易云信 IM 支持云端历史消息,历史消息的存储时长在不同的套餐包中不同,各套餐包中的限制具体请参考 增值服务

监听消息相关事件

在进行历史消息相关操作前,您可以提前注册监听相关事件。注册成功后,当对应事件发生时,SDK 会触发对应回调通知。

  • 相关回调

    • onMessageDeletedNotifications:消息删除成功回调。当本地端或多端同步删除消息成功时会触发该回调。
    • onClearHistoryNotifications:消息清空成功回调。当本地端或多端同步清空消息成功时会触发该回调。
  • 示例代码

    安卓

    调用 addMessageListener 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);
    
    V2NIMMessageListener messageListener = new V2NIMMessageListener() {
    
        @Override
        public void onMessageDeletedNotifications(List<V2NIMMessageDeletedNotification> messageDeletedNotifications) {
    
        }
    
        @Override
        public void onClearHistoryNotifications(List<V2NIMClearHistoryNotification> clearHistoryNotifications) {
    
        }
    };
    v2MessageService.addMessageListener(messageListener);
    

    如需移除消息相关监听器,可调用 removeMessageListener

    JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);
    
    v2MessageService.removeMessageListener(messageListener);
    
    iOS

    调用 addMessageListener 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    Objective-C[[[NIMSDK sharedSDK] v2MessageService] addMessageListener:listener];
    

    如需移除消息相关监听器,可调用 removeMessageListener

    Objective-C[[[NIMSDK sharedSDK] v2MessageService] removeMessageListener:listener];
    
    macOS/Windows

    调用 addMessageListener 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    C++V2NIMMessageListener listener;
    listener.onMessageDeletedNotifications = [](std::vector<V2NIMMessageDeletedNotification> messageDeletedNotification) {
        // receive message deleted notifications
    };
    listener.onClearHistoryNotifications = [](std::vector<V2NIMClearHistoryNotification> clearHistoryNotification) {
        // receive clear history notifications
    };
    messageService.addMessageListener(listener);
    

    如需移除消息相关监听器,可调用 removeMessageListener

    C++V2NIMMessageListener listener;
    // ...
    conversationService.addMessageListener(listener);
    // ...
    messageService.removeMessageListener(listener);
    
    Web/uni-app/小程序

    调用 on("EventName") 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    TypeScriptnim.V2NIMMessageService.on("onMessageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    nim.V2NIMMessageService.on("onClearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    

    如需移除消息相关监听,可调用 off("EventName")

    TypeScriptnim.V2NIMMessageService.off("onMessageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    nim.V2NIMMessageService.off("onClearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    
    Node.js/Electron

    调用 on("EventName") 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    TypeScriptv2.messageService.on("messageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    v2.messageService.on("clearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    

    如需移除消息相关监听,可调用 off("EventName")

    TypeScriptv2.messageService.off("messageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    v2.messageService.off("clearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    
    鸿蒙

    调用 on("EventName") 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    TypeScriptnim.messageService.on("onMessageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    nim.messageService.on("onClearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    

    如需移除消息相关监听,可调用 off("EventName")

    TypeScriptnim.messageService.off("onMessageDeletedNotifications", function (messageDeletedNotifications: V2NIMMessageDeletedNotification[]) {})
    nim.messageService.off("onClearHistoryNotifications", function (clearHistoryNotifications: V2NIMClearHistoryNotification[]) {})
    
    Flutter

    调用 listen 方法注册消息相关监听器,监听消息删除回调事件和消息清空回调事件。

    Dartsubsriptions.add(NimCore
        .instance.messageService.onMessageDeletedNotifications
        .listen((event) {
    //do something
    }));
    subsriptions.add(NimCore
        .instance.messageService.onClearHistoryNotifications
        .listen((event) {
    //do something
    }));
    

    如需移除消息相关监听,可调用 cancel

    Dartsubsriptions.forEach((subsription) {
    subsription.cancel();
    });
    

查询历史消息

分页查询会话内所有历史消息

调用 getMessageListExgetMessageList 方法分页查询指定会话的所有历史消息数据。

可以通过设置查询条件查询指定时间范围内具体消息类型的历史消息数据。

Android
JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);

V2NIMConversationType conversationType = V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P;
String conversationId = V2NIMConversationIdUtil.conversationId("xxx", conversationType);

V2NIMMessageListOption listOption = V2NIMMessageListOption.V2NIMMessageListOptionBuilder.builder(conversationId)
        // TODO: 根据实际情况配置
//                .withAnchorMessage()
//                .withBeginTime()
//                .withDirection()
//                .withEndTime()
//                .withLimit()
//                .withMessageTypes()
//                .withStrictMode()
        .build();

v2MessageService.getMessageListEx(listOption,
        new V2NIMSuccessCallback<V2NIMMessageListResult>() {
            @Override
            public void onSuccess(V2NIMMessageListResult result) {
                // TODO: 成功
            }
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {
                // TODO: 失败
            }
        });
iOS
Objective-CV2NIMMessageListOption *option = [[V2NIMMessageListOption alloc] init];
// 设置会话ID,来指定搜索某个会话种的消息。必传
option.conversationId = conversation;
// 设置消息类型列表,来指定查询某些类型的消息。不传则表示查询所有类型的消息。
// 这里配置为查询文本消息和文件消息。
option.messageTypes = @[@(V2NIM_MESSAGE_TYPE_TEXT), @(V2NIM_MESSAGE_TYPE_FILE)];
// 设置查找范围的较小时间戳。单位为秒。不传则表示不限制最小时间。
option.beginTime = 1700000000.0;
// 设置查找范围的较大时间戳。单位为秒。不传则表示不限制最大时间。
option.endTime = 1740000000.0;
// 设置搜索结果的最大条数。默认值为50。
option.limit = 100;
// 查询锚点。第一次查询不用传。查询完成后会回调nextPageToken字段。翻页查询时需要传入该字段。
// 查询锚点不为空时,如果查询方向为从晚到早,则要求endTime不传或者和锚点时间一致。;如果查询方向为从早到晚,则要求beginTime不传或者和锚点时间一致。
option.anchorMessage = nil;
// 查询方向,默认从晚到早查询。这里配置的就是从晚到早。
option.direction = V2NIM_QUERY_DIRECTION_DESC;
// 是否启用严格模式,默认关闭。
// 严格模式开启时,会按需查询云端数据,确保回调数据的准确性。无法确保准确性时,回调错误。
// 严格模式关闭时,模拟常规使用场景,云端补充消息失败时,会返回本地查询的结果;查询最近一页消息时,通过直接返回本地数据来避免白屏,在后台按需默默补充消息。
option.strictMode = YES;
// 是否只查询本地数据,默认关闭。开启时,strictMode会被忽略。
option.onlyQueryLocal = NO;

[[NIMSDK sharedSDK].v2MessageService getMessageListEx:option success:^(V2NIMMessageListResult * _Nonnull result) {
    // 查询成功。使用anchorMessage翻页
} failure:^(V2NIMError * _Nonnull error) {
    // 查询失败
}];
macOS/Windows
C++V2NIMMessageListOption option;
// ...
messageService.getMessageListEx(
    option,
    [=](const V2NIMMessageListResult& result) {
        // do something
    },
    [=](const V2NIMError& error) {
       // get message list failed, handle error
    });
Web/uni-app/小程序
TypeScripttry {
  const res: V2NIMMessageListResult = await nim.V2NIMMessageService.getMessageListEx({
    "conversationId": "cjhz1|1|cs6",
    "limit": 50,
    "anchorMessage": {
      "messageServerId": "111",
      "createTime": 0
    },
    "direction": 0
})
  // todo Success
} catch (err) {
  // todo error
}
Node.js/Electron
TypeScriptconst result = await v2.messageService.getMessageListEx({
    conversationId: 'conversationId'
鸿蒙
TypeScripttry {
  const res: V2NIMMessageListResult = await nim.messageService.getMessageListEx({
    "conversationId": "cjhz1|1|cs6",
    "limit": 50,
    "anchorMessage": { // if need
      "messageServerId": "111",
      // and more ...
    },
    "direction": V2NIMQueryDirection.V2NIM_QUERY_DIRECTION_DESC
})
  // todo Success
} catch (err) {
  // todo error
}
Flutter
dartawait NimCore.instance.messageService.getMessageListEx(option);

分页查询会话内所有云端历史消息

调用 getCloudMessageList 方法按条件分页获取会话内的云端历史消息数据。

可以通过设置查询条件查询指定时间范围内具体消息类型的历史消息数据。

示例代码

Android
Java// 构建云端消息查询参数
String conversationId = "xxxx";
long beginTime = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000L; // 7天前
long endTime = System.currentTimeMillis(); // 当前时间
int limit = 20; // 查询20条消息

V2NIMCloudMessageListOption option = V2NIMCloudMessageListOption.V2NIMCloudMessageListOptionBuilder
    .builder(conversationId)
    .withBeginTime(beginTime)
    .withEndTime(endTime)
    .withLimit(limit)
    .withDirection(V2NIMMessageQueryDirection.V2NIM_QUERY_DIRECTION_DESC)
    .build();

// 调用接口
NIMClient.getService(V2NIMMessageService.class).getCloudMessageList(option,
    new V2NIMSuccessCallback<V2NIMMessageListResult>() {
        @Override
        public void onSuccess(V2NIMMessageListResult result) {
            System.out.println("查询云端消息成功");
            
            List<V2NIMMessage> messages = result.getMessages();
            V2NIMMessage anchorMessage = result.getAnchorMessage();
            
            System.out.println("获取到 " + messages.size() + " 条消息");
            
            for (V2NIMMessage message : messages) {
                System.out.println("消息ID: " + message.getMessageClientId());
                System.out.println("消息内容: " + message.getText());
                System.out.println("发送时间: " + message.getCreateTime());
                System.out.println("---");
            }
            
            if (anchorMessage != null) {
                System.out.println("还有更多消息,下次查询锚点: " + anchorMessage.getMessageClientId());
            } else {
                System.out.println("没有更多消息了");
            }
        }
    },
    new V2NIMFailureCallback() {
        @Override
        public void onFailure(V2NIMError error) {
            System.out.println("查询云端消息失败, code: " + error.getCode() + 
                             ", message: " + error.getDesc());
        }
    }
);
macOS/Windows
C++V2NIMCloudMessageListOption option;
// ...
messageService.getCloudMessageList(
     option,
     [=](const V2NIMMessageListResult& result) {
         // do something
     },
     [=](const V2NIMError& error) {
         // get message list failed, handle error
     });
Node.js/Electron
TypeScriptconst result = await v2.messageService.getCloudMessageList({
    conversationId: 'conversationId'
})
鸿蒙
TypeScriptconst option: V2NIMCloudMessageListOption = {
  conversationId: 'cjl|1|cjl1',
  beginTime: undefined,
  endTime: undefined,
  anchorMessage: undefined,
  limit: 10,
  direction: V2NIMQueryDirection.V2NIM_QUERY_DIRECTION_DESC,
}

const messageListResult: V2NIMMessageListResult = await nim.messageService.getCloudMessageList(option)

批量查询指定的历史消息列表

调用 getMessageListByIds 方法根据消息客户端 ID 查询指定的历史消息。

  • 该接口只在本地数据库中查询。
  • Web 端不支持该接口。
安卓
JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);

List<String> messageClientIds = new ArrayList<>();
// TODO
// messageClientIds.add("xxx");

v2MessageService.getMessageListByIds(messageClientIds,
        new V2NIMSuccessCallback<List<V2NIMMessage>>() {
            @Override
            public void onSuccess(List<V2NIMMessage> v2NIMMessages) {

            }
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {

            }
        });
iOS
Objective-CNSArray *messageClientIds = @[@"messageClientId1",@"messageClientId2",@"messageClientIdn"];

[[[NIMSDK sharedSDK] v2MessageService] getMessageListByIds:messageClientIds
                                                success:^(NSArray<V2NIMMessage *> * _Nonnull result) {
    // result 返回消息数组

}
                                                failure:^(V2NIMError * _Nonnull error) {
    // error 包含错误原因
}];
macOS/Windows
C++std::vector<std::string> messageClientIds;
// ...
messageService.getMessageListByIds(
    messageClientIds,
    [](std::vector<V2NIMMessage> messages) {
        for (auto&& message : messages) {
            // do something
        }
    },
    [](V2NIMError error) {
        // get message list by ids failed, handle error
    });
Web/uni-app/小程序

因平台属性,暂不支持。

Node.js/Electron
TypeScriptconst messages = await v2.messageService.getMessageListByIds(messageClientIds)
鸿蒙
TypeScriptconst messageIds: string[] //消息 ID 数组
const result = await nim.messageService.getMessageListByIds(messageIds)
Flutter
Dartawait NimCore.instance.messageService.getMessageListByIds(messageClientIds);

分页查询云端 Thread 历史消息

调用 getThreadMessageList 方法根据 Thread 根消息分页获取所有 Thread 子消息。

为避免触发请求频控,若云端会话数据同步已完成(收到 onSyncFinished),建议您改用 getLocalThreadMessageList 方法获取本地 Thread 历史消息列表。

示例代码如下:

安卓
JavaV2NIMThreadMessageListOption option = new V2NIMThreadMessageListOption();
// messageRefer field is mandatory and is used to determine a root message. It can be filled directly with a message body or a V2NIMMessageRefer object can be constructed based on the message body's fields.
option.setMessageRefer(rootMessageRefer);
// The following fields are optional
// beginTime and endTime define the time range of the query. Fill with 0 to indicate no restriction.
option.setBeginTime(0L);
option.setEndTime(0L);
// For the first page, leave this field blank. When paging, fill in the serverId of the message closest to the target page's current page. For example, anchorMessage represents the earliest message on the current page, allowing the current request to page backward (earlier events). Query 20 messages earlier than anchorMessage (excluding itself).
option.setExcludeMessageServerId("123456");
// Maximum number of messages to be retrieved
option.setLimit(20);
// Query direction, default is V2NIM_QUERY_DIRECTION_DESC
option.setDirection(V2NIMQueryDirection.V2NIM_QUERY_DIRECTION_DESC);

NIMClient.getService(V2NIMMessageService.class).getThreadMessageList(option, v2NIMThreadMessageListResult -> {
    //Query successful
}, error -> {
    //Query failed
});
iOS
Objective-CV2NIMThreadMessageListOption *option = [[V2NIMThreadMessageListOption alloc] init];
// messageRefer 字段必填,此字段用于确定一条根消息。可以直接填消息体,也可以根据消息体的字段,构造一个 V2NIMMessageRefer 对象
option.messageRefer = rootMessage;
//下面的字段均为可选字段
// beginTime 和 endTime 划定了查询的时间范围,填 0 表示不做限制。
option.beginTime = 0;
option.endTime = 1715331571.927; //anchorMessage.createTime
// 第一页不填,翻页时填写距离目标页最近的当前页的消息的 serverId。
// 如 anchorMessage 表示当前页中最早的一条消息,则当前请求可以实现向前(事件更早)翻页。查询比 anchorMessage 早(不包括自己)的 20 条消息
option.excludeMessageServerId = @"123456"; //anchorMessage.messageServerId
// 查询出的消息条数上限
option.limit = 20;
// 查询方向。DESC 为按时间戳从大到小查询
option.direction = V2NIM_QUERY_DIRECTION_DESC;

// 调用接口查询消息
[[NIMSDK sharedSDK].v2MessageService getThreadMessageList:option success:^(V2NIMThreadMessageListResult *result) {
        // 查询成功
    } failure:^(V2NIMError *error) {
        // 查询失败
    }];
macOS/Windows
C++V2NIMTheadMessageListOption threadMessageListOption;
// ...
messageService.getThreadMessageList(
    threadMessageListOption,
    [](V2NIMThreadMessageListResult response) {
        // do something
    },
    [](V2NIMError error) {
        // get message list by refers failed, handle error
    });
Web/uni-app/小程序
TypeScripttry {
    const result = await nim.V2NIMMessageService.getThreadMessageList({
      messageRefer: {
          "senderId": "account1",
          "receiverId": "account2",
          "messageClientId": "21a7e3d43a7afdf52e11f61d9753f99c",
          "messageServerId": "231689624",
          "createTime": 1715222453441,
          "conversationType": 1,
          "conversationId": "account1|1|account2"
      },
      "limit": 50
  })
} catch(err) {
    console.error('getAddApplicationUnreadCount Error:', err)
}
Node.js/Electron
TypeScripttry {
  const result = await v2.messageService.getThreadMessageList({
      messageRefer: {
          "senderId": "account1",
          "receiverId": "account2",
          "messageClientId": "21a7e3d43a7afdf52e11f61d9753f99c",
          "messageServerId": "231689624",
          "createTime": 1715222453441,
          "conversationType": 1,
          "conversationId": "account1|1|account2"
      },
      "limit": 50
  })
} catch(err) {
    console.error('getAddApplicationUnreadCount Error:', err)
}
鸿蒙
TypeScripttry {
    const result = await nim.messageService.getThreadMessageList({
      messageRefer: {
          "senderId": "account1",
          "receiverId": "account2",
          "messageClientId": "21a7e3d43a7afdf52e11f61d9753f99c",
          "messageServerId": "231689624",
          "createTime": 1715222453441,
          "conversationType": 1,
          "conversationId": "account1|1|account2"
      },
      "limit": 50
  })
} catch(err) {
    console.error('getAddApplicationUnreadCount Error:', err)
}
Flutter
Dartawait NimCore.instance.messageService.getThreadMessageList(threadMessageListOption);

查询本地 Thread 历史消息

调用 getLocalThreadMessageList 方法根据 Thread 根消息获取所有本地 Thread 子消息。

示例代码如下:

安卓
Java// messageRefer 字段用于确定一条根消息。可以直接填消息体,也可以根据消息体的字段,构造一个 V2NIMMessageRefer 对象
V2NIMMessageRefer messageRefer = rootMessage;
NIMClient.getService(V2NIMMessageService.class).getLocalThreadMessageList(messageRefer, v2NIMThreadMessageListResult -> {
    //Query successful
}, error -> {
    //Query failed
});
iOS
Objective-C// messageRefer 字段用于确定一条根消息。可以直接填消息体,也可以根据消息体的字段,构造一个 V2NIMMessageRefer 对象
V2NIMMessageRefer *messageRefer = rootMessage;
// 调用接口查询消息
[[NIMSDK sharedSDK].v2MessageService getLocalThreadMessageList:messageRefer success:^(V2NIMThreadMessageListResult *result) {
    // 查询成功
} failure:^(V2NIMError *error) {
    // 查询失败
}];
macOS/Windows
C++V2NIMMessageRefer messageRefer;
// ...
messageService.getLocalThreadMessageList(
    messageRefer,
    [](V2NIMThreadMessageListResult response) {
        // do something
    },
    [](V2NIMError error) {
        // get message list by refers failed, handle error
    });
Node.js/Electron
Typescriptconst messageRefer = {
          "senderId": "account1",
          "receiverId": "account2",
          "messageClientId": "21a7e3d43a7afdf52e11f61d9753f99c",
          "messageServerId": "231689624",
          "createTime": 1715222453441,
          "conversationType": 1,
          "conversationId": "account1|1|account2"
      } as V2NIMMessageRefer

const result = await v2.messageService.getLocalThreadMessageList(messageRefer)
鸿蒙
Typescriptconst messageRefer = {
          "senderId": "account1",
          "receiverId": "account2",
          "messageClientId": "21a7e3d43a7afdf52e11f61d9753f99c",
          "messageServerId": "231689624",
          "createTime": 1715222453441,
          "conversationType": 1,
          "conversationId": "account1|1|account2"
      } as V2NIMMessageRefer

const result = await nim.messageService.getLocalThreadMessageList(messageRefer)
Flutter
Dartawait NimCore.instance.messageService.getLocalThreadMessageList(messageRefer);

删除历史消息

网易云信 IM 的删除消息接口,可通过配置 onlyDeleteLocal 参数选择是否只删除本地消息。

  • 只删除本地,本地会将该消息标记为删除,后续查询本地消息时会过滤该消息,界面不展示,卸载重装会再次显示。

  • 删除本地的同时删除云端对应的消息,删除后消息无法恢复。

    删除云端消息功能需要在 网易云信控制台 单独开通,只有开通后,该功能才能使用。若未开通,请参考 开启功能项 进行开通。

删除指定单条消息

调用 deleteMessage 方法删除指定的单条消息。

删除指定消息后,若消息还未读,则应用总消息未读数会减 1。

若需要删除的消息处于未发送成功状态,则只删除本地消息,不涉及云端消息,因此不会触发多端同步。删除本地消息的同时删除对应的云端消息后,会多端同步该操作。

本地或云端删除消息成功后,SDK 会返回删除成功回调 onMessageDeletedNotifications

安卓
JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);

// V2NIMMessage deleteMessage = ; // 被删除的消息

v2MessageService.deleteMessage(deleteMessage, "xxx", false,
        new V2NIMSuccessCallback<Void>() {
            @Override
            public void onSuccess(Void unused) {

            }
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {

            }
        });
iOS
Objective-C[[[NIMSDK sharedSDK] v2MessageService] deleteMessage:message
                                    serverExtension:@"json String"
                                    onlyDeleteLocal:YES
                                            success:^{
}
                                            failure:^(V2NIMError * _Nonnull error) {
    //error 包含错误原因
}];
macOS/Windows
C++V2NIMMessage message;
// ...
messageService.deleteMessage(
    message,
    "serverExtension",
    false,
    []() {
        // delete message succeeded
    },
    [](V2NIMError error) {
        // delete message failed, handle error
    }
);
Web/uni-app/小程序
TypeScripttry {
await nim.V2NIMMessageService.deleteMessage(message, 'serverExtension');
// todo: Success
} catch (err) {
// todo: error
}
Node.js/Electron
TypeScripttry {
  await v2.messageService.deleteMessage(message, 'serverExtension', true)
  // todo Success
} catch (err) {
  // todo error
}
鸿蒙
TypeScripttry {
await nim.messageService.deleteMessage(message, 'serverExtension')
// todo Success
} catch (err) {
// todo error
}
Flutter
Dartawait NimCore.instance.messageService.deleteMessage(message, serverExtension, onlyDeleteLocal);

批量删除指定消息列表

调用 deleteMessages 方法删除指定会话内的消息列表。

删除指定消息列表后,若消息还未读,则应用总消息未读数会减去对应的删除的消息数量。

若需要删除的消息处于未发送成功状态,则只删除本地消息,不涉及云端消息,因此不会触发多端同步。删除本地消息的同时删除对应的云端消息后,会多端同步该操作。

本地或云端删除消息成功后,SDK 会返回删除成功回调 onMessageDeletedNotifications

安卓
JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);

// List<V2NIMMessage> messages = ; // 被删除的消息

v2MessageService.deleteMessages(messages, "xxx", false,
        new V2NIMSuccessCallback<Void>() {
            @Override
            public void onSuccess(Void unused) {

            }
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {

            }
        });
iOS
Objective-C[[[NIMSDK sharedSDK] v2MessageService] deleteMessages:@[message]
                                        serverExtension:@"json String"
                                        onlyDeleteLocal:YES
                                                success:^{
}
                                                failure:^(V2NIMError * _Nonnull error) {
    //error 包含错误原因
}];
macOS/Windows
C++std::vector<V2NIMMessage> messages;
// ...
messageService.deleteMessages(
    messages,
    "serverExtension",
    false,
    []() {
        // delete messages succeeded
    },
    [](V2NIMError error) {
        // delete messages failed, handle error
    });
Web/uni-app/小程序
TypeScripttry {
await nim.V2NIMMessageService.deleteMessages(messages, 'serverExtension')
// todo Success
} catch (err) {
// todo error
}
Node.js/Electron
TypeScripttry {
  await v2.messageService.deleteMessages(messages, 'serverExtension', true)
  // todo Success
} catch (err) {
  // todo error
}
鸿蒙
TypeScripttry {
await nim.messageService.deleteMessages(messages, 'serverExtension')
// todo Success
} catch (err) {
// todo error
}
Flutter
Dartawait NimCore.instance.messageService.deleteMessages(messages, serverExtension, onlyDeleteLocal);

清空历史消息

调用 clearHistoryMessage 方法清空指定会话内的所有消息,支持指定是否同步删除漫游消息以及是否多端同步清空操作。您也可以自由选择清空 本地和云端仅本地 的历史消息。

本地或云端清空消息成功后,SDK 会返回清空成功回调 onClearHistoryNotifications

安卓
JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);

V2NIMConversationType conversationType = V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P;
String conversationId = V2NIMConversationIdUtil.conversationId("xxx", conversationType);

V2NIMClearHistoryMessageOption clearOption = V2NIMClearHistoryMessageOption.V2NIMClearHistoryMessageOptionBuilder.builder(conversationId)
   // TODO: 根据实际情况配置
   //                .withDeleteRoam()
   //                .withExtension()
   //                .withOnlineSync()
   //                .withClearMode()
   .build();

v2MessageService.clearHistoryMessage(clearOption,
   new V2NIMSuccessCallback<Void>() {
    @Override
    public void onSuccess(Void unused) {

    }
   },
   new V2NIMFailureCallback() {
    @Override
    public void onFailure(V2NIMError error) {

    }
   });
iOS
Objective-CV2NIMClearHistoryMessageOption *option = [[V2NIMClearHistoryMessageOption alloc] init];
option.conversationId = [V2NIMConversationIdUtil p2pConversationId:@"xxx"];
// TODO: 根据实际情况配置
// option.deleteRoam =
// option.onlineSync =
// option.serverExtension =
// option.clearMode =

[[NIMSDK sharedSDK].v2MessageService clearHistoryMessage:option success:^{
    // 清除成功
} failure:^(V2NIMError * _Nonnull error) {
    // 清除失败
}];
macOS/Windows
C++V2NIMClearHistoryMessageOption option;
option.conversationId = V2NIMConversationIdUtil::p2pConversationId("target_account_id");
messageService.clearHistoryMessage(
    option,
    []() {
        // clear history message succeeded
    },
    [](V2NIMError error) {
        // clear history message failed, handle error
    });
Web/uni-app/小程序
TypeScriptconst conversationId = nim.V2NIMConversationIdUtil.p2pConversationId("TARGET_ACCOUNT_ID")
const option = {
    conversationId: conversationId,
    deleteRoam: true,
    onlineSync: true,
    serverExtension: 'ext',
    clearMode: V2NIMConst.V2NIMClearHistoryMode.V2NIM_CLEAR_HISTORY_MODE_ALL
}
await nim.V2NIMMessageService.clearHistoryMessage(option)
Node.js/Electron
TypeScriptawait v2.messageService.clearHistoryMessage(option)
鸿蒙
TypeScriptconst option = {
    conversationId: conversationId,
    deleteRoam: true,
    onlineSync: true,
    serverExtension: 'ext',
    clearMode: V2NIMClearHistoryMode.V2NIM_CLEAR_HISTORY_MODE_ALL
}
await nim.messageService.clearHistoryMessage(option)
Flutter
Dartawait NimCore.instance.messageService.clearHistoryMessage(option);

清空指定的漫游会话消息

调用 clearRoamingMessage 方法清空指定的漫游会话消息,建议单次最多删除 50 个漫游会话。

清空的漫游会话越多,请求耗时越长,因此若数据量打,建议分次操作。

安卓
JavaList<String> conversationIds = new ArrayList<>();
conversationIds.add("xxx1|1|xxx2");
conversationIds.add("xxx1|1|xxx3");
NIMClient.getService(V2NIMMessageService.class).clearRoamingMessage(
        conversationIds,
        new V2NIMSuccessCallback<Void>() {
            @Override
            public void onSuccess(Void result) {
                System.out.println("clearRoamingMessage success");
            }
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {
                System.out.println("clearRoamingMessage failed");
            }
        }
);
macOS/Windows
C++nstd::vector<nstd::string> conversationIds;
conversationIds.push_back("conversationId1");
conversationIds.push_back("conversationId2");
messageService.clearRoamingMessage(
    conversationIds,
    [](void) {
        // clear roaming message succeeded
    },
    [](V2NIMError error) {
        // clear roaming message failed, handle error
    });
Web/uni-app/小程序
TypeScripttry {
    await nim.V2NIMMessageService.clearRoamingMessage(['xxx1|1|xxx2', 'xxx1|1|xxx3'])
    // success
} catch (e) {
    // failed
}
Node.js/Electron
TypeScriptawait v2.messageService.clearRoamingMessage(['conversationId1', 'conversationId2'])
鸿蒙
TypeScripttry {
    await nim.messageService.clearRoamingMessage(['xxx1|1|xxx2', 'xxx1|1|xxx3'])
    // success
} catch (e) {
    // failed
}

相关接口

安卓/iOS/macOS/Windows
API 说明
addMessageListener 注册消息相关监听器
removeMessageListener 取消注册消息相关监听器
getMessageList 按消息查询配置项分页获取所有历史消息
getMessageListEx 按消息查询配置项分页获取所有历史消息
getMessageListByIds 根据消息客户端 ID 获取历史消息
deleteMessage 删除单条消息
deleteMessages 批量删除消息列表
clearHistoryMessage 清空会话内历史消息
getThreadMessageList 分页获取云端 Thread 历史消息列表
getLocalThreadMessageList 获取本地 Thread 历史消息列表
getCloudMessageList 按消息查询配置项分页获取云端消息
clearRoamingMessage 清空指定的漫游会话消息
Web/uni-app/小程序/Node.js/Electron/鸿蒙
API 说明
on("EventName") 注册消息相关监听器
off("EventName") 取消注册消息相关监听器
getMessageList 按消息查询配置项分页获取所有历史消息
getMessageListEx 按消息查询配置项分页获取所有历史消息
getMessageListByIds 根据消息客户端 ID 获取历史消息
deleteMessage 删除单条消息
deleteMessages 批量删除消息列表
clearHistoryMessage 清空会话内历史消息
getThreadMessageList 分页获取云端 Thread 历史消息列表
getLocalThreadMessageList 获取本地 Thread 历史消息列表
getCloudMessageList 按消息查询配置项分页获取云端消息
clearRoamingMessage 清空指定的漫游会话消息
Flutter
API 说明
listen 注册消息相关监听器
cancel 取消注册消息相关监听器
getMessageList 按消息查询配置项分页获取所有历史消息
getMessageListEx 按消息查询配置项分页获取所有历史消息
getMessageListByIds 根据消息客户端 ID 获取历史消息
deleteMessage 删除单条消息
deleteMessages 批量删除消息列表
clearHistoryMessage 清空会话内历史消息
getThreadMessageList 分页获取云端 Thread 历史消息列表
getLocalThreadMessageList 获取本地 Thread 历史消息列表
此文档是否对你有帮助?
有帮助
去反馈
  • 支持平台
  • 准备工作
  • 监听消息相关事件
  • 查询历史消息
  • 分页查询会话内所有历史消息
  • 分页查询会话内所有云端历史消息
  • 批量查询指定的历史消息列表
  • 分页查询云端 Thread 历史消息
  • 查询本地 Thread 历史消息
  • 删除历史消息
  • 删除指定单条消息
  • 批量删除指定消息列表
  • 清空历史消息
  • 清空指定的漫游会话消息
  • 相关接口