Starter Deal! First 3 month from only  $9.9 /month!
Starter Deal! First 3 month from only  $9.9 /month!
Grab It Now 
Chat
  • Web
    • TUIKit
      • Overview
      • Installaton
        • TUIKit
          • Vue
          • React
        • TUIChat Only
          • Vue
      • Features
        • Reactions
        • Read Receipt
        • Typing Status
        • User Online Status
      • Themes
        • Setting UI Styles
          • Web
          • Mobile
      • Customization
        • Customize Messages
      • Localization
    • SDK
      • Install Chat SDK
      • Initialize Chat SDK
      • Login and Logout
      • Client APIs
      • Message
        • Overview
        • Send a Message
        • Receive a Message
        • Historical Message
        • Forward Messages
        • Modify a Message
        • Delete Messages
        • Clear History Message
        • Recall a Message
        • Send an Online Message
        • Message Read Receipt
        • Query Messages
        • Targeted Group Message
        • Do not Notify
        • Key-Value Extensions
        • Translation
      • Conversation
        • Overview
        • Conversation List
        • Get Conversations
        • Unread Count
        • Pin Conversations
        • Delete Conversations
        • Mark
        • Conversation Group
      • Group
        • Overview
        • Group Management
        • Group Profile
        • Group Member Management
        • Group Member Profile
        • Custom Group Attribute
        • Group Counter
      • Community Topic
        • Community Management
      • User Profile and Relationship Chain
        • User Profile
        • User Status
        • Friend Management
        • Friend List
        • Block List
  • Android
    • Run Demo
    • UIKit
      • Overview
      • Getting Started
      • Installation
        • TUIKit
        • TUIChat Only
      • Features
        • Reactions
        • Read Receipt
        • User Online Status
        • Search Messages
      • Customization
        • Customize Messages
        • Customize Emojis and Stickers
      • Localization
    • SDK
      • Install Chat SDK
      • Initialize Chat SDK
      • Login and Logout
      • Message
        • Overview
        • Send a Message
        • Receive a Message
        • Retrieve Messages
        • Forward Messages
        • Modify a Message
        • Insert a Message
        • Delete Messages
        • Clear History Messages
        • Recall a Message
        • Send an Online Message
        • Message Read Receipt
        • Query Messages
        • Metions
        • Targeted Group Message
        • Do not Notify
        • Key-Value Extensions
        • Reactions
        • Translation
        • Pin Messages
      • Conversation
        • Overview
        • Conversation List
        • Get Conversations
        • Unread Count
        • Pin Conversations
        • Delete Conversations
        • Draft
        • Mark
        • Conversation Group
      • Group
        • Overview
        • Manage Group
        • Profile
        • Manage Members
        • Member Profile
        • Attribute
        • Counter
      • Community and Topic
        • Manage Community
        • Permission Group
      • User
        • User Profile
        • User Status
        • Manage Friends
        • Friend Group
        • Block Lists
      • Local Search
        • Search Messages
        • Search Friends
        • Search Groups
        • Search Group Members
      • Signaling
      • API Reference
        • Java
  • iOS and macOS
    • Run Demo
    • UIKit
      • Overview
      • Getting Started
      • Installation
        • TUIKit
        • TUIChat Only
      • Features
        • Reactions
        • Read Receipt
        • User Online Status
        • Search Messages
      • Customization
        • Customize Messages
        • Customize Emojis and Stickers
      • Localization
    • SDK
      • Installation
        • iOS
        • macOS
      • Initialize Chat SDK
      • Login and Logout
      • Message
        • Overview
        • Send a Message
        • Receive a Message
        • Retrieve Messages
        • Forward Messages
        • Modify a Message
        • Insert a Message
        • Delete Messages
        • Clear History Messages
        • Recall a Message
        • Send an Online Message
        • Message Read Receipt
        • Query Messages
        • Metions
        • Targeted Group Messages
        • Do not Notify
        • Key-Value Extensions
        • Reactions
        • Translation
        • Pin Messages
      • Conversation
        • Overview
        • Conversation List
        • Get Conversations
        • Unread Count
        • Pin Conversations
        • Delete Conversations
        • Draft
        • Mark
        • Conversation Group
      • Group
        • Overview
        • Manage Group
        • Profile
        • Manage Members
        • Member Profile
        • Attribute
        • Counter
      • Community and Topic
        • Manage Community
        • Permission Group
      • User
        • User Profile
        • User Status
        • Manage Friends
        • Friend Group
        • Block Lists
      • Local Search
        • Search Messages
        • Search Friends
        • Search Groups
        • Search Group Members
      • Signaling
      • API Reference
        • Swift
        • Objective-C
  • Windows
    • SDK
      • Install Chat SDK
      • Initialize Chat SDK
      • Login and Logout
      • Message
        • Overview
        • Send a Message
        • Receive a Message
        • Retrieve Messages
        • Forward Messages
        • Modify a Message
        • Insert a Message
        • Delete Messages
        • Clear History Messages
        • Recall a Message
        • Send an Online Message
        • Message Read Receipt
        • Query Messages
        • Metions
        • Targeted Group Messages
        • Do not Notify
        • Key-Value Extensions
        • Reactions
        • Translation
        • Pin Messages
      • Conversation
        • Overview
        • Conversation List
        • Get Conversations
        • Unread Count
        • Pin Conversations
        • Delete Conversations
        • Draft
        • Mark
        • Conversation Group
      • Group
        • Overview
        • Manage Group
        • Profile
        • Manage Members
        • Member Profile
        • Attribute
        • Counter
      • Community and Topic
        • Manage Community
        • Permission Group
      • User
        • User Profile
        • User Status
        • Manage Friends
        • Friend Group
        • Block Lists
      • Local Search
        • Search Messages
        • Search Friends
        • Search Groups
        • Search Group Members
      • Signaling
      • API Reference
        • C++
        • C
  • Flutter
    • Run Demo
    • UIKIT
      • Overview
      • Installation
        • integrated
      • Features
        • Local Search
        • Offline Push
        • Online Status
        • Typing Status
        • Message Read Receipt
        • Message Reactions
        • Internationalization
        • Adding Custom Messages
        • Emoji & Stickers
      • Customization
        • Modifying UI Themes
        • Setting UI Styles
    • SDK
      • Install Chat SDK
        • Install
      • Initialize Chat SDK
        • Initialize
      • Login And Logout
        • Login and Logout
      • Message
        • Message Overview
        • Sending Message
        • Receiving Message
        • Historical Message
        • Forwarding Message
        • Modifying Message
        • Message Inserting
        • Deleting Message
        • Clearing Messages
        • Recalling Message
        • Online Message
        • Read Receipt
        • Querying Message
        • Group @ Message
        • Targeted Group Message
        • Notification Muting
        • Message Extension
      • Conversation
        • Conversation Overview
        • Conversation List
        • Getting Conversation
        • Conversation Unread Count
        • Pinning Conversation to the Top
        • Deleting Conversation
        • Conversation Draft
        • Conversation Group
      • Group
        • Group Overview
        • Group Management
        • Group Profile
        • Group Member Management
        • Group Member Profile
        • Custom Group Attribute
      • User
        • User Profile
        • Friend Management
        • Friend List
        • Blocklist
      • Offline Push
        • Offline Push
      • Signaling
        • Signaling Management
      • Local Search
        • Searching for Message
        • Searching for Friend
        • Searching Group
        • Searching for Group Member
      • API Reference
        • Client APIs
  • React Native
    • Run Demo
    • SDK
      • SDK Integration
      • Initialization
      • Login and Logout
      • Message
        • Message Overview
        • Sending Message
        • Receiving Message
        • Historical Message
        • Forwarding Message
        • Modifying Message
        • Message Inserting
        • Deleting Message
        • Clearing Messages
        • Recalling Message
        • Online Message
        • Read Receipt
        • Querying Message
        • Group @ Message
        • Targeted Group Message
        • Notification Muting
        • Message Extension
      • Group
        • Overview
        • Group Management
        • Group Profile
        • Group Member Management
        • Group Member Profile
        • Custom Group Attribute
        • Community Management
      • User
        • User Profile
        • Friend Management
        • Friend List
        • Blocklist
      • Offline Push
        • Offline Push
      • Local Search
        • Searching for Message
        • Searching for Friend
        • Searching Group
        • Searching for Group Member
      • Signaling
        • Signaling Management
  • Unity(Game Solution)
    • Run Demo
    • SDK
      • SDK Integration
      • Initialization
      • Login and Logout
      • Message
        • Message Overview
        • Sending Message
        • Receiving Message
        • Historical Message
        • Forwarding Message
        • Modifying Message
        • Deleting Message
        • Clearing Messages
        • Recalling Message
        • Online Message
        • Read Receipt
        • Querying Message
        • Group @ Message
        • Targeted Group Message
        • Notification Muting
        • Message Extension
      • Conversation
        • Conversation Overview
        • Conversation List
        • Getting Conversation
        • Conversation Unread Count
        • Pinning Conversation to the Top
        • Deleting Conversation
        • Conversation Draft
        • Conversation Mark
        • Conversation Group
      • Group
        • Group Overview
        • Group Management
        • Group Profile
        • Group Member Management
        • Group Member Profile
        • Custom Group Attribute
        • Group Counter
      • User
        • User Profile
        • User Status
        • Friend Management
        • Friend List
        • Blocklist
  • Unreal Engine(Game Solution)
    • SDK
      • SDK Integration
  • Free Demos
  • Server APIs
    • Generating UserSig
    • RESTful APIs
      • RESTful API Overview
      • RESTful API List
      • Message Related
        • Send Message
          • Sending One-to-One Messages to One User
          • Sending One-to-One Messages to Multiple Users
          • Sending Ordinary Messages in a Group
          • Sending System Messages in a Group
          • Broadcast Message of Audio-Video Group
          • Importing One-to-One Messages
          • Importing Group Messages
        • Historical Message
          • Modifying Historical One-to-one Messages
          • Modifying Historical Group Messages
          • Pulling Historical One-to-one Messages
          • Pulling Historical Group Messages
        • Delete Message
          • Deleting Messages Sent by a Specified User
        • Withdraw Message
          • Recalling One-to-One Messages
          • Recalling Group Messages
        • Read Receipt
          • Marking One-to-One Messages as Read
          • Pulling Group Message Read Receipt Details
          • Pulling Read Receipts for Group Messages
        • Message Extension
          • Pulling the Message Extension of a One-to-One Message
          • Configuring Message Extension for a One-to-One Message
          • Pulling Message Extension of a Group Message
          • Configuring Message Extension for a Group Message
        • Pushing to All Users
          • API for Pushing to All Users
          • Pushing to All Users
          • Setting Application Attribute Names
          • Getting Application Attribute Names
          • Getting User Attributes
          • Setting User Attributes
          • Deleting User Attributes
          • Getting User Tags
          • Adding User Tags
          • Deleting User Tags
          • Deleting All Tags of a User
      • Session Related
        • Conversation List
          • Pulling a conversation list
        • Session Unread Count
          • Setting the Unread Message Count of a Member
          • Querying Unread One-to-One Message Count
        • Delete Session
          • Deleting a conversation
        • Session Grouping Tag
          • Creating Conversation Group Data
          • Updating Conversation Group Data
          • Deleting Conversation Group Data
          • Creating or Updating Conversation Mark Data
          • Searching for Conversation Group Marks
          • Pulling Conversation Group Mark Data
      • Group Related
        • Group Management
          • Getting All Groups in an App
          • Creating a Group
          • Disbanding a Group
          • Getting the Groups a User Has Joined
        • Group Information
          • Getting Group Profiles
          • Modifying the Profile of a Group
          • Importing a Group Profile
        • Group Member Management
          • Adding Group Members
          • Deleting Group Members
          • Banning Group Members
          • Unbanning Group Members
          • Bulk Muting and Unmuting
          • Getting the List of Muted Group Members
          • Changing Group Owner
          • Querying the Roles of Users in a Group
          • Importing Group Members
        • Group Member Information
          • Getting Group Member Profiles
          • Modifying the Profile of a Group Member
        • Group Custom Attributes
          • Getting Group Custom Attributes
          • Modifying Group Custom Attributes
          • Clearing Group Custom Attributes
          • Resetting Group Custom Attributes
          • Deleting Group Custom Attributes
        • Live Group Management
          • Getting the Number of Online Users in an Audio-Video Group
          • Getting the List of Online Members in Audio-Video Group
          • Setting Audio-Video Group Member Marks
          • Getting the List of Banned Group Members.
        • Community Management
          • Creating Topic
          • Deleting Topic
          • Getting Topic Profile
          • Modifying Topic Profile
          • Importing Topic Profiles
        • Group Counter
          • Getting Group Counters
          • Updating Group Counters
          • Deleting Group Counters
      • User Management
        • Account Management
          • Importing a Single Account
          • Importing Multiple Accounts
          • Deleting Accounts
          • Querying Accounts
        • User Information
          • Setting Profiles
          • Pulling Profiles
        • User Status
          • Invalidating Account Login States
          • Querying Account Online Status
        • Friend Management
          • Adding Friends
          • Importing Friends
          • Updating Friends
          • Deleting Friends
          • Deleting All Friends
          • Verifying Friends
          • Pulling Friends
          • Pulling Specified Friends
        • Friend Lists
          • Adding Lists
          • Deleting Lists
          • Pulling Lists
        • Blocklist
          • Blocklisting Users
          • Unblocklisting Users
          • Pulling a Blacklist
          • Verifying Users on a Blocklist
      • Global Mute Management
        • Setting Global Mute
        • Querying Global Mute
      • Operations Management
        • Pulling Operations Data
        • Downloading Recent Messages
        • Getting Server IP Addresses
      • Chatbots
        • Pulling Chatbot Accounts
        • Creating Chatbot Accounts
        • Deleting Chatbot Accounts
    • Webhooks
      • Webhook Overview
      • Webhook Command List
      • Operations Management Callbacks
        • API Overclocking Alarm Callbacks
      • Online Status Webhooks
        • Status Change Webhooks
      • Relationship Chain Webhooks
        • After a Profile Is Updated
        • Before a Friend Is Added
        • Before a Friend Request Is Responded
        • After a Friend Is Added
        • After a Friend Is Deleted
        • After a User Is Added to Blocklist
        • After a User Is Removed from Blocklist
      • One-to-One Message Webhooks
        • Before a One-to-One Message Is Sent
        • After a One-to-One Message Is Sent
        • After a One-to-One message Is Marked as Read
        • After A One-to-One Message Is Recalled
      • Group Webhooks
        • Before a Group Is Created
        • After a Group Is Created
        • Before Applying to Join a Group
        • Before Inviting a User to a Group
        • After a User Joins a Group
        • After a User Leaves a Group
        • Before Group Message Is Sent
        • After a Group Message Is Sent
        • After a Group Is Full
        • After a Group Is Disbanded
        • After Group Profile Is Modified
        • Callback After Recalling Group Messages
        • Webhook for Online and Offline Status of Audio-Video Group Members
        • Webhook for Exceptions When Group Messages Are Sent
        • Before a Topic Is Created
        • After a Topic Is Created
        • After a Topic Is Deleted
        • Topic Profile Change Webhook
        • Callback After Group Member Profile Changed
        • Callback After Group Attribute Changed
        • Callback After Read Receipt
        • Callback After the Group Owner Changed
      • Webhook Mutual Authentication Configuration Guide
        • Apache Mutual Authentication Configuration
        • Nginx Mutual Authentication Configuration
      • Chatbot webhooks
        • Chatbot Passthrough Message Callback
  • Console Guide
    • Creating and Upgrading an Application
    • Basic Configuration
    • Feature Configuration
    • Account Management
    • Group Management
    • Webhook Configuration
  • Product Introduction
    • Message Management
      • One-to-One Message
      • Message Storage
      • Offline Push
      • Group Message
      • Message Formats
    • Account System
      • Login Authentication
      • Online Status Management
    • Group Related
      • Group System
      • Group Management
    • User Profile and Relationship Chain
      • Profile Management
      • Relationship Chain Management
  • Purchase Guide
    • Billing Overview
    • Pricing
  • Error Codes
Chat

Unread Count

Overview

A user's conversation list usually contains multiple conversations. If there is a new message in one of the conversations, a badge needs to be displayed in the list cell to indicate the unread count. After the user clicks to enter the conversation and goes back to the conversation list, the unread count is cleared, and the badge disappears. The Chat SDK also supports getting the total unread message count of all or some conversations (using filters), which is displayed at the bottom tab of the conversation list.
This document describes how to implement the conversation unread count notification feature.


Getting the Total Unread Count of All Conversations

In general cases, to get the total unread count of all the conversations, you can traverse the conversation list to get the V2TIMConversation information of each conversation and add the unreadCount values of all the V2TIMConversation objects to get the final result and display it on the UI. The Chat SDK provides the getTotalUnreadMessageCount API to query the total unread count of all the conversations. When the total unread count changes, the SDK will notify the latest total unread count through the onTotalUnreadMessageCountChanged callback.
Note:
1. This feature is supported only by the SDK of the Enhanced edition on v5.3.425 or later.
2. This feature applies only to work groups (Work), public groups (Public), and communities (Community), but not to audio-video groups (AVChatRoom) or meeting groups (Meeting). For more information on the group types, see Group Overview.
Below are detailed steps.

Getting the total unread count of all conversations

Call getTotalUnreadMessageCount (Android / iOS and macOS / Windows) to get the total unread message count of all conversations and display it on the UI.
Sample code:
Android
iOS and macOS
Windows
V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
@Override
public void onSuccess(Long aLong) {
Log.i("imsdk", "success");
}

@Override
public void onError(int code, String desc) {
Log.i("imsdk", "failure, code:" + code + ", desc:" + desc);
}
});
[[V2TIMManager sharedInstance] getTotalUnreadMessageCount:^(UInt64 totalCount) {
// Obtained successfully. `totalCount` is the total unread message count of all conversations.
// Update the unread count on the UI
} fail:^(int code, NSString *desc) {
// Failed to obtain
}];
template <class T>
class ValueCallback final : public V2TIMValueCallback<T> {
public:
using SuccessCallback = std::function<void(const T&)>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;

ValueCallback() = default;
~ValueCallback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
}

void OnSuccess(const T& value) override {
if (success_callback_) {
success_callback_(value);
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
};

auto callback = new ValueCallback<uint64_t>{};
callback->SetCallback(
[=](const uint64_t& count) {
// Got the total unread count of all conversations successfully
delete callback;
},
[=](int error_code, const V2TIMString& error_message) {
// Failed to get the total unread count of all conversations
delete callback;
});

V2TIMManager::GetInstance()->GetConversationManager()->GetTotalUnreadMessageCount(callback);

Notification of a change in the total unread count

Call addConversationListener (Android / iOS and Mac / Windows) to add a conversation listener to receive notifications of a change in the total unread count of all conversations (such notifications can be received only after the getTotalUnreadMessageCount API is called).
You can get the changed total unread count in onTotalUnreadMessageCountChanged (Android / iOS and macOS / Windows) of V2TIMConversationListener.
Sample code:
Android
iOS and macOS
Windows
public void onTotalUnreadMessageCountChanged(long totalUnreadCount) {
// Received a notification of a change in the total unread count of all conversations
Log.i("imsdk", "onTotalUnreadMessageCountChanged");
}
// Add a conversation listener
[[V2TIMManager sharedInstance] addConversationListener:self];

// Received a notification of a change in the total unread count of all conversations
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
// `totalUnreadCount` is the total unread count.
}
class ConversationListener final : public V2TIMConversationListener {
public:
/**
* Notification of the change of the total unread message count of all conversations (supported by 5.3.425 or later)
*
* @note
* - The total unread message count excludes the unread message count of Do-Not-Disturb conversations (conversations whose message receiving option is
* V2TIM_NOT_RECEIVE_MESSAGE or V2TIM_RECEIVE_NOT_NOTIFY_MESSAGE).
*/
void OnTotalUnreadMessageCountChanged(uint64_t totalUnreadCount) override {
// Received a notification of a change in the total unread count of all conversations
}
// Other member functions...
};

// Add a conversation event listener. Keep `conversationListener` valid before the listener is removed to ensure event callbacks are received.
ConversationListener conversationListener;
V2TIMManager::GetInstance()->GetConversationManager()->AddConversationListener(&conversationListener);

Getting the Total Unread Message Count of Some Conversations by Filters

The Chat SDK provides the getUnreadMessageCountByFilter API for you to query the total unread message count of some conversations based on filters. To listen for the changes of the total unread message count of some conversations based on filters, call subscribeUnreadMessageCountByFilter to register the listening. When the total unread count under the specified filters changes, the SDK will notify you of the latest total unread count through the onUnreadMessageCountChangedByFilter callback.
Note:
1. This feature is supported only by the SDK of the Enhanced edition on v7.0.3754 or later.
2. This feature applies only to work groups (Work), public groups (Public), and communities (Community), but not to audio-video groups (AVChatRoom) or meeting groups (Meeting). For more information on the group types, see Group Overview.
Below are detailed steps.

Getting the total unread message count of some conversations

Call getUnreadMessageCountByFilter (Android / iOS and Mac / Windows) to get the total unread message count of some conversations and update it on the UI. The filter condition V2TIMConversationListFilter is described as follows:
Attribute
Definition
Description
type
Conversation type (0 indicates that this item is not filtered.)
One-to-one or group conversation
conversationGroup
Conversation group name (If no value is entered, this item is not filtered.)
It is not the group name but the conversation group name. For more information, see Conversation Group.
markType
Conversation tag type (0 indicates that this item is not filtered.)
For more information, see Conversation Tag.
Sample code:
Android
iOS and macOS
Windows
V2TIMConversationListFilter filter = new V2TIMConversationListFilter();
filter.setConversationType(V2TIMConversation.V2TIM_GROUP);
filter.setConversationGroup("conversation_group");
filter.setMarkType(V2TIMConversation.V2TIM_CONVERSATION_MARK_TYPE_STAR);

V2TIMManager.getConversationManager().getUnreadMessageCountByFilter(filter, new V2TIMValueCallback<Long>() {
@Override
public void onSuccess(Long totalUnreadCount) {
tvLog.setText("getUnreadMessageCountByFilter success, totalUnreadCount:" + totalUnreadCount);
}

@Override
public void onError(int code, String desc) {
tvLog.setText("getUnreadMessageCountByFilter failed");
}
});
V2TIMConversationListFilter *filter = [[V2TIMConversationListFilter alloc] init];
filter.type = V2TIM_GROUP;
filter.conversationGroup = @"conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;

[[V2TIMManager sharedInstance] getUnreadMessageCountByFilter:filter succ:^(UInt64 totalUnreadCount) {
[self appendString:[NSString stringWithFormat:@"getUnreadMessageCountByFilter success totalUnreadCount:%llu", totalUnreadCount]];
} fail:^(int code, NSString *desc) {
[self appendString:[NSString stringWithFormat:@"getUnreadMessageCountByFilter failed"]];
}];
template <class T>
class ValueCallback final : public V2TIMValueCallback<T> {
public:
using SuccessCallback = std::function<void(const T&)>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;

ValueCallback() = default;
~ValueCallback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
}

void OnSuccess(const T& value) override {
if (success_callback_) {
success_callback_(value);
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
};

auto callback = new ValueCallback<uint64_t>{};
callback->SetCallback(
[=](const uint64_t& count) {
// Got the total unread count successfully
delete callback;
},
[=](int error_code, const V2TIMString& error_message) {
// Failed to get the total unread count
delete callback;
});

V2TIMConversationListFilter filter;
filter.type = V2TIM_GROUP;
filter.conversationGroup = "conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;

V2TIMManager::GetInstance()->GetConversationManager()->GetUnreadMessageCountByFilter(filter, callback);

Registering the listening for the changes of the total unread message count of some conversations

Call addConversationListener (Android / iOS and macOS / Windows) to add a conversation listener. Then call the subscribeUnreadMessageCountByFilter (Android / iOS and macOS / Windows) API to register the listening for the changes of the total unread message count under specified filters.
You can get the changed total unread count in onUnreadMessageCountChangedByFilter (Android / iOS and macOS / Windows) of V2TIMConversationListener.
You can specify multiple filters for the unread count listening. The filter parameter in the onUnreadMessageCountChangedByFilter callback lists the filters specified when subscribeUnreadMessageCountByFilter is called. The filter parameter contains the conversationType, conversationGroup, and markType fields. We can distinguish between different filters by checking whether all three fields are the same.
Sample code:
Android
iOS and macOS
Windows
// Add a conversation listener
V2TIMManager.getConversationManager().addConversationListener(conversationListener);

// Register the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter filter = new V2TIMConversationListFilter();
filter.setConversationType(V2TIMConversation.V2TIM_GROUP);
filter.setConversationGroup("conversation_group");
filter.setMarkType(V2TIMConversation.V2TIM_CONVERSATION_MARK_TYPE_STAR);
V2TIMManager.getConversationManager().subscribeUnreadMessageCountByFilter(filter);

// Notification on the change of the total unread message count under specified filters
public void onUnreadMessageCountChangedByFilter(V2TIMConversationListFilter filter, long totalUnreadCount) {
// `filter` indicates the filter conditions. `totalUnreadCount` indicates the total unread message count.
Log.i(TAG, "onUnreadMessageCountChangedByFilter:" + totalUnreadCount + "\n");
}
// Add a conversation listener
[[V2TIMManager sharedInstance] addConversationListener:self];

// Register the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter *filter = [[V2TIMConversationListFilter alloc] init];
filter.type = V2TIM_GROUP;
filter.conversationGroup = @"conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;
[[V2TIMManager sharedInstance] subscribeUnreadMessageCountByFilter:filter];

// Notification on the change of the total unread message count under specified filters
- (void)onUnreadMessageCountChangedByFilter:(V2TIMConversationListFilter *)filter totalUnreadCount:(UInt64)totalUnreadCount {
// `filter` indicates the filter conditions. `totalUnreadCount` indicates the total unread message count.
}
class ConversationListener final : public V2TIMConversationListener {
public:
// Notification on the change of the total unread message count under specified filters
void OnUnreadMessageCountChangedByFilter(const V2TIMConversationListFilter &filter, uint64_t totalUnreadCount) override {
// `filter` indicates the filter conditions. `totalUnreadCount` indicates the total unread message count.
}
// Other member functions...
};

// Add a conversation event listener. Keep `conversationListener` valid before the listener is removed to ensure event callbacks are received.
ConversationListener conversationListener;
V2TIMManager::GetInstance()->GetConversationManager()->AddConversationListener(&conversationListener);

// Register the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter filter;
filter.type = V2TIM_GROUP;
filter.conversationGroup = "conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;
V2TIMManager::GetInstance()->GetConversationManager()->SubscribeUnreadMessageCountByFilter(filter);

Canceling the listening for the changes of the total unread message count of some conversations

Call the unsubscribeUnreadMessageCountByFilter (Android / iOS and macOS / Windows) API to cancel the listening for the changes of the total unread message count under specified filters.
Sample code:
Android
iOS and macOS
Windows
// Cancel the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter filter = new V2TIMConversationListFilter();
filter.setConversationType(V2TIMConversation.V2TIM_GROUP);
filter.setConversationGroup("conversation_group");
filter.setMarkType(V2TIMConversation.V2TIM_CONVERSATION_MARK_TYPE_STAR);
V2TIMManager.getConversationManager().unsubscribeUnreadMessageCountByFilter(filter);
// Cancel the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter *filter = [[V2TIMConversationListFilter alloc] init];
filter.type = V2TIM_GROUP;
filter.conversationGroup = @"conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;
[[V2TIMManager sharedInstance] unsubscribeUnreadMessageCountByFilter:filter];
// Cancel the listening for the changes of the total unread message count under specified filters
V2TIMConversationListFilter filter;
filter.type = V2TIM_GROUP;
filter.conversationGroup = "conversation_group";
filter.markType = V2TIM_CONVERSATION_MARK_TYPE_STAR;
V2TIMManager::GetInstance()->GetConversationManager()->UnsubscribeUnreadMessageCountByFilter(filter);

Clearing the Conversation Unread Count

After the user clicks to enter a conversation and goes back to the conversation list, the unread count needs to be cleared, after which the badge in the conversation list needs to disappear. The Chat SDK provides three APIs to clear the unread count for different conversation types:
markC2CMessageAsRead is used to clear the unread count of a one-to-one conversation.
markGroupMessageAsRead is used to clear the unread count of a group conversation.
markAllMessageAsRead is used to clear the unread count of all the conversations.
Below are detailed steps.
Note:
This feature is supported only by the SDK of the Enhanced edition on v5.8.1668 or later.

One-to-one chat

Call markC2CMessageAsRead (Android / iOS and macOS / Windows) to clear the unread count of a specified one-to-one conversation.
Sample code:
Android
iOS and macOS
Windows
String userID = "userID";
V2TIMManager.getMessageManager().markC2CMessageAsRead(userID, new V2TIMCallback() {
@Override
public void onSuccess() {
Log.i("imsdk", "success");
}

@Override
public void onError(int code, String desc) {
Log.i("imsdk", "failure, code:" + code + ", desc:" + desc);
}
});
[[V2TIMManager sharedInstance] markC2CMessageAsRead:@"conversationID" // ID of the target one-to-one conversation
succ:^{
// Cleared the unread count successfully
} fail:^(int code, NSString *msg) {
// Failed to clear the unread count
}];
class Callback final : public V2TIMCallback {
public:
using SuccessCallback = std::function<void()>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;

Callback() = default;
~Callback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
}

void OnSuccess() override {
if (success_callback_) {
success_callback_();
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
};

V2TIMString userID = u8"userID";

auto callback = new Callback;
callback->SetCallback(
[=]() {
// Cleared the unread count successfully
delete callback;
},
[=](int error_code, const V2TIMString& error_message) {
// Failed to clear the unread count
delete callback;
});

V2TIMManager::GetInstance()->GetMessageManager()->MarkC2CMessageAsRead(userID, callback);
After the markC2CMessageAsRead is called successfully:
1. If the caller has called addConversationListener to add a conversation listener, it will receive the onConversationChanged callback and update the UI.
2. The sender will receive the onRecvC2CReadReceipt callback that contains the timestamp when the conversation unread count is cleared.
Sample code:
Android
iOS and macOS
Windows
public void onConversationChanged(List<V2TIMConversation> conversationList) {
// The caller received the notification of a change in the conversation information.
Log.i("imsdk", "onConversationChanged");
}

public void onRecvC2CReadReceipt(List<V2TIMMessageReceipt> receiptList) {
// Read receipt for the one-to-one message
Log.i("imsdk", "onRecvC2CReadReceipt");
}
// Add a conversation listener
[[V2TIMManager sharedInstance] addConversationListener:self];

// The caller received the notification of a change in the conversation information.
- (void)onConversationChanged:(NSArray<V2TIMConversation*> *)conversationList {
// Update the UI based on the `V2TIMConversation` in `conversationList`, for example, clear the badge in the cell of the one-to-one conversation
}

// Read receipt for the one-to-one message
- (void)onRecvC2CReadReceipt:(NSArray<V2TIMMessageReceipt *> *)receiptList {

}
class ConversationListener final : public V2TIMConversationListener {
public:
/**
* If the key information of some conversations changes (for example, the unread count changes, or the last message is updated),
* use "lastMessage -> timestamp" to sort the conversation list again.
*
* @param conversationList Conversation list
*/
void OnConversationChanged(const V2TIMConversationVector& conversationList) override {}
// Other members …
};

// Add a conversation event listener. Keep `conversationListener` valid before the listener is removed to ensure event callbacks are received.
ConversationListener conversationListener;
V2TIMManager::GetInstance()->GetConversationManager()->AddConversationListener(&conversationListener);

class AdvancedMsgListener final : public V2TIMAdvancedMsgListener {
public:
/**
* One-to-one message read notification (This callback is received when the recipient calls the `MarkC2CMessageAsRead` API.
* The callback contains only the UserID and read timestamp information of the recipient.)
*
* @param receiptList Read receipt list
*/
void OnRecvC2CReadReceipt(const V2TIMMessageReceiptVector& receiptList) override {}
// Other members …
};

// Add an event listener for advanced messages. Keep `advancedMsgListener` valid before it is removed to ensure event callbacks are received.
AdvancedMsgListener advancedMsgListener;
V2TIMManager::GetInstance()->GetMessageManager()->AddAdvancedMsgListener(&advancedMsgListener);

Group chat

Call markGroupMessageAsRead (Android / iOS and macOS / Windows) to clear the unread message count of a specified group conversation.
Sample code:
Android
iOS and macOS
Windows
String groupID = "groupID";
V2TIMManager.getMessageManager().markGroupMessageAsRead(groupID, new V2TIMCallback() {
@Override
public void onSuccess() {
Log.i("imsdk", "success");
}

@Override
public void onError(int code, String desc) {
Log.i("imsdk", "failure, code:" + code + ", desc:" + desc);
}
});
[[V2TIMManager sharedInstance] markGroupMessageAsRead:@"conversationID" // ID of the target group conversation
succ:^{
// Cleared the unread count successfully
} fail:^(int code, NSString *msg) {
// Failed to clear the unread count
}];
class Callback final : public V2TIMCallback {
public:
using SuccessCallback = std::function<void()>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;

Callback() = default;
~Callback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
}

void OnSuccess() override {
if (success_callback_) {
success_callback_();
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
};

V2TIMString groupID = u8"groupID";

auto callback = new Callback;
callback->SetCallback(
[=]() {
// Cleared the unread count successfully
delete callback;
},
[=](int error_code, const V2TIMString& error_message) {
// Cleared the unread count successfully
delete callback;
});

V2TIMManager::GetInstance()->GetMessageManager()->MarkGroupMessageAsRead(groupID, callback);
After markGroupMessageAsRead is called successfully, if the caller has called addConversationListener to add a conversation listener, it will receive the onConversationChanged callback and update the UI.
Sample code:
Android
iOS and macOS
Windows
public void onConversationChanged(List<V2TIMConversation> conversationList) {
// The caller received the notification of a change in the conversation information.
Log.i("imsdk", "onConversationChanged");
}
// Add a conversation listener
[[V2TIMManager sharedInstance] addConversationListener:self];

// The caller received the notification of a change in the conversation information.
- (void)onConversationChanged:(NSArray<V2TIMConversation*> *)conversationList {
// Update the UI based on the `V2TIMConversation` in `conversationList`, for example, clear the badge in the cell of the group conversation
}
class ConversationListener final : public V2TIMConversationListener {
public:
void OnConversationChanged(const V2TIMConversationVector& conversationList) override {}
// The caller received the notification of a change in the conversation information.
};

// Add a conversation event listener. Keep `conversationListener` valid before the listener is removed to ensure event callbacks are received.
ConversationListener conversationListener;
V2TIMManager::GetInstance()->GetConversationManager()->AddConversationListener(&conversationListener);

All conversations

Call markAllMessageAsRead (Android / iOS and macOS / Windows) to clear the unread message count of all conversations.
Sample code:
Android
iOS and macOS
Windows
V2TIMManager.getMessageManager().markAllMessageAsRead(new V2TIMCallback() {
@Override
public void onSuccess() {
Log.i("imsdk", "success");
}

@Override
public void onError(int code, String desc) {
Log.i("imsdk", "failure, code:" + code + ", desc:" + desc);
}
});
[[V2TIMManager sharedInstance] markAllMessageAsRead:^{
// Cleared the unread count successfully
} fail:^(int code, NSString *desc) {
// Failed to clear the unread count
}];
class Callback final : public V2TIMCallback {
public:
using SuccessCallback = std::function<void()>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;

Callback() = default;
~Callback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
}

void OnSuccess() override {
if (success_callback_) {
success_callback_();
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
};

auto callback = new Callback;
callback->SetCallback(
[=]() {
// Cleared the unread count successfully
delete callback;
},
[=](int error_code, const V2TIMString& error_message) {
// Failed to clear the unread count
delete callback;
});

V2TIMManager::GetInstance()->GetMessageManager()->MarkAllMessageAsRead(callback);
After markAllMessageAsRead is called successfully, if the caller has called addConversationListener in advance to add a conversation listener, it will receive the onConversationChanged callback and update the UI.
Sample code:
Android
iOS and macOS
Windows
public void onConversationChanged(List<V2TIMConversation> conversationList) {
// Received the notification of a change in the conversation information
Log.i("imsdk", "onConversationChanged");
}
// Add a conversation listener
[[V2TIMManager sharedInstance] addConversationListener:self];

// The caller received the notification of a change in the conversation information.
- (void)onConversationChanged:(NSArray<V2TIMConversation*> *)conversationList {
// Update the UI, for example, clear the badge on the bottom tab of the conversation list
}
class ConversationListener final : public V2TIMConversationListener {
public:
void OnConversationChanged(const V2TIMConversationVector& conversationList) override {}
// The caller received the notification of a change in the conversation information.
};

// Add a conversation event listener. Keep `conversationListener` valid before the listener is removed to ensure event callbacks are received.
ConversationListener conversationListener;
V2TIMManager::GetInstance()->GetConversationManager()->AddConversationListener(&conversationListener);


Sending a Message Excluded from the Conversation Unread Count

In normal cases, both one-to-one messages and group messages that are sent will be included in the unread count. Specifically, you can get the conversation unread count through the unreadCount of the V2TIMConversation conversation object. If you want to send messages that will not be included in the unread count, such as tips or control messages, when calling sendMessage, you can:
Android: call setExcludedFromUnreadCount and set it to true.
iOS/Windows: set the message object isExcludedFromUnreadCount to YES/true.
For how to use sendMessage, see Sending Message.
Note:
The setExcludedFromUnreadCount or isExcludedFromUnreadCount parameter is supported only by the SDK of the Enhanced edition on v5.3.425 or later.
Sample code:
Android
iOS and macOS
Windows
// Create the message object
V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createTextMessage(content);
// Set not to update the `lastMessage` of the conversation
v2TIMMessage.setExcludedFromUnreadCount(true);

// Send the message
V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "userID", null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
@Override
public void onSuccess(V2TIMMessage v2TIMMessage) {
Log.i("imsdk", "success");
}

@Override
public void onProgress(int progress) {
Log.i("imsdk", "progress:" + progress);
}

@Override
public void onError(int code, String desc) {
Log.i("imsdk", "failure, code:" + code + ", desc:" + desc);
}
});
// Create the message object
V2TIMMessage *message = [[V2TIMManager sharedInstance] createTextMessage:@"This is a signaling message"];

// Set the identifier for excluding from the unread message count
message.isExcludedFromUnreadCount = YES;

// Send the message
[[V2TIMManager sharedInstance] sendMessage:msg receiver:@"userA" groupID:nil
priority:V2TIM_PRIORITY_DEFAULT onlineUserOnly:YES offlinePushInfo:nil progress:^(uint32_t progress) {
} succ:^{
// Message sent successfully
} fail:^(int code, NSString *msg) {
// Failed to send the message
}];
class SendCallback final : public V2TIMSendCallback {
public:
using SuccessCallback = std::function<void(const V2TIMMessage&)>;
using ErrorCallback = std::function<void(int, const V2TIMString&)>;
using ProgressCallback = std::function<void(uint32_t)>;

SendCallback() = default;
~SendCallback() override = default;

void SetCallback(SuccessCallback success_callback, ErrorCallback error_callback,
ProgressCallback progress_callback) {
success_callback_ = std::move(success_callback);
error_callback_ = std::move(error_callback);
progress_callback_ = std::move(progress_callback);
}

void OnSuccess(const V2TIMMessage& message) override {
if (success_callback_) {
success_callback_(message);
}
}
void OnError(int error_code, const V2TIMString& error_message) override {
if (error_callback_) {
error_callback_(error_code, error_message);
}
}
void OnProgress(uint32_t progress) override {
if (progress_callback_) {
progress_callback_(progress);
}
}

private:
SuccessCallback success_callback_;
ErrorCallback error_callback_;
ProgressCallback progress_callback_;
};

// Create the message object
V2TIMMessage message = V2TIMManager::GetInstance()->GetMessageManager()->CreateTextMessage(u8"content");
// Set not to update the `lastMessage` of the conversation
message.isExcludedFromUnreadCount = true;

auto callback = new SendCallback{};
callback->SetCallback([=](const V2TIMMessage& message) { delete callback; },
[=](int error_code, const V2TIMString& error_message) { delete callback; },
[=](uint32_t progress) {});

V2TIMManager::GetInstance()->GetMessageManager()->SendMessage(
message, u8"userID", {}, V2TIMMessagePriority::V2TIM_PRIORITY_NORMAL, false, {}, callback);