Android Conversation: Unread Count
Retrieve an accurate unread messages count in various scenarios on Android
Total Unread Count
To get the total unread count, use BrandMessengerManager.getTotalUnreadCount in a non-main thread.
Thread t = new Thread() {
@Override
public void run() {
int count = BrandMessengerManager.getTotalUnreadCount(context);
}
};
t.start();
Thread {
var count = BrandMessengerManager.getTotalUnreadCount(context)
}
Real-time update of count
To update unread message count real time for any incoming messages, you will receive BrandMessengerConstants.BRAND_MESSENGER_UNREAD_COUNT broadcast. Define the broadcast in your activity using the example below:
BroadcastReceiver unreadCountBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (BrandMessengerConstants.BRAND_MESSENGER_UNREAD_COUNT.equals(intent.getAction())) {
MessageDatabaseService messageDatabaseService = new MessageDatabaseService(context);
int unreadCount = messageDatabaseService.getTotalUnreadCount();
//Update unread count in UI
}
}
};
val unreadCountBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (BrandMessengerConstants.BRAND_MESSENGER_UNREAD_COUNT == intent.action) {
val messageDatabaseService = MessageDatabaseService(context)
val unreadCount = messageDatabaseService.totalUnreadCount
//Update unread count in UI
}
}
}
Register the broadcast
You can register the broadcast in your activity, or any other place where you want to use it. Here is an example:
LocalBroadcastManager.getInstance(this).registerReceiver(unreadCountBroadcastReceiver, new IntentFilter(BrandMessengerConstants.BRAND_MESSENGER_UNREAD_COUNT));
LocalBroadcastManager.getInstance(this).registerReceiver(unreadCountBroadcastReceiver, IntentFilter(BrandMessengerConstants.BRAND_MESSENGER_UNREAD_COUNT));
Unregister the broadcast
You need to unregister the broadcast once the activity or app is closed. Use this example:
LocalBroadcastManager.getInstance(this).unregisterReceiver(unreadCountBroadcastReceiver);
LocalBroadcastManager.getInstance(this).unregisterReceiver(unreadCountBroadcastReceiver);
Updated 9 months ago