QuickBlox Documentation

QuickBlox provides powerful Chat API and SDK to add real-time messaging and video calls to your web and mobile apps. Learn how to integrate QuickBlox across multiple platforms and devices. Check out our detailed guides to make integration easy and fast.

Chat

Learn how to enable chat functionality for your app.

Chat API is built on top of real-time (XMPP) protocol. In order to use it, you need to setup real-time connection with QuickBlox Chat server and use it to exchange data. By default real-time Chat works over secure TLS connection.

Before you begin

  1. Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.
  2. Register a QuickBlox account. This is a matter of a few minutes and you will be able to use this account to build your apps.
  3. Configure QuickBlox SDK for your app. Check out our Setup page for more details.
  4. Create a user session to be able to use QuickBlox functionality. See our Authentication page to learn how to do it.

Connect to Chat server

To connect to the Chat server use the code snippet below.

// Chat connection configuration
QBChatService.ConfigurationBuilder configurationBuilder = new QBChatService.ConfigurationBuilder();
configurationBuilder.setSocketTimeout(300);
configurationBuilder.setUseTls(true);
configurationBuilder.setKeepAlive(true);
configurationBuilder.setAutojoinEnabled(false);
configurationBuilder.setAutoMarkDelivered(true);
configurationBuilder.setReconnectionAllowed(true);
configurationBuilder.setAllowListenNetwork(true);
configurationBuilder.setPort(5223);

QBChatService.setConfigurationBuilder(configurationBuilder);

QBChatService chatService = QBChatService.getInstance();

chatService.login(qbUser, new QBEntityCallback() {
    @Override
    public void onSuccess(Object o, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
// Chat connection configuration
val configurationBuilder = QBChatService.ConfigurationBuilder()
configurationBuilder.socketTimeout = 300
configurationBuilder.isUseTls = true
configurationBuilder.isKeepAlive = true
configurationBuilder.isAutojoinEnabled = false
configurationBuilder.setAutoMarkDelivered(true)
configurationBuilder.isReconnectionAllowed = true
configurationBuilder.setAllowListenNetwork(true)
configurationBuilder.port = 5223

QBChatService.setConfigurationBuilder(configurationBuilder)

val chatService = QBChatService.getInstance()

chatService.login(qbUser, object : QBEntityCallback<Void> {
    override fun onSuccess(o: Void?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

Parameters

Description

setSocketTimeout

Chat socket read timeout in seconds. Default: 60.

setUseTls

TLS security mode used when making the connection.
Default: true .

setKeepAlive

Keep-alive option for a socket connection. Keep-alive is the option allowing to detect a stale connection. Default: true.

setAutojoinEnabled

Automatically join dialogs loaded or created on the server. Default: false.

setAutoMarkDelivered

Automatically mark the received messages as delivered.
Default: true .

setReconnectionAllowed

Android SDK reconnects automatically to the Chat server when the connection to the server is lost. Default: true.

setAllowListenNetwork

Allow SDK to listen to changes of network states. Default: true.

setPort

Chat connection port number.
Default: 5223.

Check if connected to Chat server

Check the connection state using ConnectionListener.

ConnectionListener connectionListener = new ConnectionListener() {
    @Override
    public void connected(XMPPConnection xmppConnection) {

    }

    @Override
    public void authenticated(XMPPConnection xmppConnection, boolean b) {

    }

    @Override
    public void connectionClosed() {

    }

    @Override
    public void connectionClosedOnError(Exception e) {

    }

    @Override
    public void reconnectionSuccessful() {

    }

    @Override
    public void reconnectingIn(int i) {

    }

    @Override
    public void reconnectionFailed(Exception e) {

    }
};

QBChatService.getInstance().addConnectionListener(connectionListener);
val connectionListener = object : ConnectionListener {
    override fun connected(xmppConnection: XMPPConnection) {

    }

    override fun authenticated(xmppConnection: XMPPConnection, b: Boolean) {

    }

    override fun connectionClosed() {

    }

    override fun connectionClosedOnError(e: Exception) {

    }

    override fun reconnectionSuccessful() {

    }

    override fun reconnectingIn(i: Int) {

    }

    override fun reconnectionFailed(e: Exception) {

    }
}

QBChatService.getInstance().addConnectionListener(connectionListener)

Disconnect from Chat server

Disconnect from the Chat server using the snippet below.

final QBChatService chatService = QBChatService.getInstance();
boolean isLoggedIn = chatService.isLoggedIn();
if (!isLoggedIn) {
    return;
}

chatService.logout(new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
        chatService.destroy();
    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val chatService = QBChatService.getInstance()
val isLoggedIn = chatService.isLoggedIn
if (!isLoggedIn) {
    return
}

chatService.logout(object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
        chatService.destroy()
    }

    override fun onError(e: QBResponseException?) {

    }
})

Autoreconnect to Chat

The SDK reconnects automatically when the connection to the Chat server is lost. There is a way to disable it and then manage it manually.

QBChatService.getInstance().setReconnectionAllowed(false);
QBChatService.getInstance().isReconnectionAllowed = false

Chat in background

When your application goes background, you should disconnect from the Chat server to be able to receive offline messages. When your application goes foreground, you should connect to the Chat server to become online and start sending and receiving messages.

Use androidx.lifecycle.LifecycleObserver to determine when the application goes background.

public class BackgroundListener implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onBackground() {
        QBChatService.getInstance().logout(new QBEntityCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid, Bundle bundle) {
                QBChatService.getInstance().destroy();
            }

            @Override
            public void onError(QBResponseException e) {

            }
        });
    }
}
class BackgroundListener : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    internal fun onBackground() {
        QBChatService.getInstance().logout(object : QBEntityCallback<Void> {
            override fun onSuccess(v: Void?, b: Bundle?) {
                QBChatService.getInstance().destroy()
            }

            override fun onError(e: QBResponseException?) {
                
            }
        })
    }
}

Make sure to add an instance of the created lifecycle observer class to the androidx.lifecycle.ProcessLifecycleOwner() to process lifecycle changes within your app.

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new BackgroundListener());
    } 
}
class App : Application() {

    override fun onCreate() {
        super.onCreate()
        ProcessLifecycleOwner.get().lifecycle.addObserver(BackgroundListener())
    }
}

Dialogs

All chats between users are organized in dialogs. There are 3 types of dialogs:

  • 1-1 dialog - a conversation between 2 users.
  • group dialog - a conversation between the specified list of users.
  • public dialog - an open conversation. Any user from your app can subscribe to it.

You need to create a new dialog and then use it to chat with other users. You also can obtain a list of your existing dialogs.

Create new dialog

Create 1-1 dialog

You need to pass QBDialogType.PRIVATE as a type and ID of an opponent you want to create a chat with.

ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(123);
 
QBChatDialog dialog = new QBChatDialog();
dialog.setType(QBDialogType.PRIVATE);
dialog.setOccupantsIds(occupantIdsList);
 
// or just use DialogUtils
//QBChatDialog dialog = DialogUtils.buildPrivateDialog(recipientId);
 
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog result, Bundle params) {
 
    }
 
    @Override
    public void onError(QBResponseException responseException) {
 
    }
});
val occupantIdsList = ArrayList<Int>()
occupantIdsList.add(123)

val dialog = QBChatDialog()
dialog.type = QBDialogType.PRIVATE
dialog.setOccupantsIds(occupantIdsList)

// or just use DialogUtils
//QBChatDialog dialog = DialogUtils.buildPrivateDialog(recipientId);

QBRestChatService.createChatDialog(dialog).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(result: QBChatDialog?, params: Bundle?) {

    }

    override fun onError(responseException: QBResponseException?) {

    }
})

Create group dialog

You need to pass QuickBlox DialogType.GROUP as a type and IDs of opponents, you want to create a chat with.

ArrayList<Integer> occupantIdsList = new ArrayList<Integer>();
occupantIdsList.add(123);
occupantIdsList.add(234);
occupantIdsList.add(345);
occupantIdsList.add(456);

QBChatDialog dialog = new QBChatDialog();
dialog.setName("Group chat");
dialog.setType(QBDialogType.GROUP);
dialog.setOccupantsIds(occupantIdsList);

// or just use DialogUtils
// QBChatDialog dialog = DialogUtils.buildDialog("Chat with Friends", QBDialogType.GROUP, occupantIdsList);

QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog result, Bundle params) {

    }

    @Override
    public void onError(QBResponseException responseException) {

    }
});
val occupantIdsList = ArrayList<Int>()
occupantIdsList.add(123)
occupantIdsList.add(234)
occupantIdsList.add(345)
occupantIdsList.add(456)

val dialog = QBChatDialog()
dialog.name = "Group chat"
dialog.type = QBDialogType.GROUP
dialog.setOccupantsIds(occupantIdsList)

// or just use DialogUtils
// QBChatDialog dialog = DialogUtils.buildDialog("Chat with Friends", QBDialogType.GROUP, occupantIdsList);

QBRestChatService.createChatDialog(dialog).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(result: QBChatDialog?, params: Bundle?) {

    }

    override fun onError(responseException: QBResponseException?) {

    }
})

Create public dialog

It's possible to create a public dialog, so any user from your application can subscribe to it. There is no a list with occupants, this dialog is just open for everybody. You need to pass QBDialogType.PUBLIC_GROUP as a type.

QBChatDialog dialog = new QBChatDialog();
dialog.setName("Public group chat");
dialog.setType(QBDialogType.PUBLIC_GROUP);

QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog result, Bundle params) {

    }

    @Override
    public void onError(QBResponseException responseException) {

    }
});
val dialog = QBChatDialog()
dialog.name = "Public group chat"
dialog.type = QBDialogType.PUBLIC_GROUP

QBRestChatService.createChatDialog(dialog).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(result: QBChatDialog?, params: Bundle?) {

    }

    override fun onError(responseException: QBResponseException?) {

    }
})

Retrieve list of dialogs

It's common to request all your conversations on every app login.

QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(50);
//requestBuilder.setSkip(100);
//requestBuilder.sortAsc("last_message_date_sent");

QBRestChatService.getChatDialogs(null, requestBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatDialog>>() {
    @Override
    public void onSuccess(ArrayList<QBChatDialog> result, Bundle params) {
      
    }

    @Override
    public void onError(QBResponseException responseException) {

    }
});
val requestBuilder = QBRequestGetBuilder()
requestBuilder.limit = 50
//requestBuilder.setSkip(100);
//requestBuilder.sortAsc("last_message_date_sent");

QBRestChatService.getChatDialogs(null, requestBuilder).performAsync(object : QBEntityCallback<ArrayList<QBChatDialog>> {
    override fun onSuccess(result: ArrayList<QBChatDialog>?, params: Bundle?) {
      
    }

    override fun onError(responseException: QBResponseException?) {

    }
})

It will return all your 1-1 dialogs, group dialog, and public dialogs you are subscribed to.

If you want to retrieve only conversations updated after some specific date time, you can pass the filter. For example, you can apply gt filter to updated_at and id fields using requestBuilder. This is useful if you cache conversations somehow and do not want to obtain the whole list of your conversations on every app start. You can use the other filters:
- lt (Less Than operator)
- lte (Less Than or Equal to ...)
- gt (Greater Than operator)
- gte (Greater Than or Equal to ...)
- eq (Equals to ...)
- ne (Not Equal to ...)
- in (Contained IN array ...)
- nin (Not contained IN array)
- all (ALL contained IN array)
- ctn (Contains ...)

Update dialog

Update a group dialog name or photo using QBRequestUpdateBuilder.

QBChatDialog dialog = new QBChatDialog();
dialog.setDialogId("dsfsd934329hjhkda98793j2");  // To make updates - the dialog must contain dialogId
dialog.setName("Team room");
dialog.setPhoto("https://new_photo_url"); // or it can be ID of uploaded File with QBContent

QBRequestUpdateBuilder requestBuilder = new QBRequestUpdateBuilder();

QBRestChatService.updateChatDialog(dialog, requestBuilder).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog updatedDialog, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val dialog = QBChatDialog()
dialog.dialogId = "dsfsd934329hjhkda98793j2"  // To make updates - the dialog must contain dialogId
dialog.name = "Team room"
dialog.photo = "https://new_photo_url" // or it can be ID of uploaded File with QBContent

val requestBuilder = QBRequestUpdateBuilder()

QBRestChatService.updateChatDialog(dialog, requestBuilder).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(updatedDialog: QBChatDialog?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

Add/Remove occupants

You can add/remove occupants in group and public dialogs.

// To add or remove users you should pass whole QBUser model or it's ID (user.getId)
QBDialogRequestBuilder qbRequestBuilder = new QBDialogRequestBuilder();

qbRequestBuilder.addUsers(usersToAdd.toArray(new QBUser[usersToAdd.size()]));
qbRequestBuilder.removeUsers(usersToAdd.toArray(new QBUser[usersToRemove.size()]));

QBRestChatService.updateChatDialog(qbChatDialog, qbRequestBuilder).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
// To add or remove users you should pass whole QBUser model or it's ID (user.getId)
val qbRequestBuilder = QBDialogRequestBuilder()

qbRequestBuilder.addUsers(*usersToAdd.toTypedArray())
qbRequestBuilder.removeUsers(*usersToAdd.toTypedArray())

QBRestChatService.updateChatDialog(qbChatDialog, qbRequestBuilder).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(qbChatDialog: QBChatDialog?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

❗️

Important note

Only group dialog owner can remove other users from a group chat.

Remove dialog

The following snippet is used to delete a conversation.

String dialogId = qbChatDialog.getDialogId();
boolean forceDelete = false;

QBRestChatService.deleteDialog(dialogId, forceDelete).performAsync(new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val dialogId = qbChatDialog.dialogId
val forceDelete = false

QBRestChatService.deleteDialog(dialogId, forceDelete).performAsync(object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

Or, you can use multiple dialogs deleting.

StringifyArrayList<String> qbDialogsIDs = new StringifyArrayList<>();
for (QBChatDialog dialog : qbChatDialogs) {
    qbDialogsIDs.add(dialog.getDialogId());
}

boolean forceDelete = false;

QBRestChatService.deleteDialogs(qbDialogsIDs, forceDelete, null).performAsync(new QBEntityCallback<ArrayList<String>>() {
    @Override
    public void onSuccess(ArrayList<String> strings, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val qbDialogsIDs = StringifyArrayList<String>()
for (dialog in qbChatDialogs) {
    qbDialogsIDs.add(dialog.dialogId)
}

val forceDelete = false

QBRestChatService.deleteDialogs(qbDialogsIDs, forceDelete, null).performAsync(object : QBEntityCallback<ArrayList<String>> {
    override fun onSuccess(strings: ArrayList<String>?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

🚧

Pay attention

This request will remove this conversation for a current user, but other users still will be able to chat there. The forceDelete parameter is used to completely remove the dialog. Only group dialog owner can remove the group dialog for all users.

Chat history

Every chat conversation stores its chat history that you can retrieve.

QBMessageGetBuilder messageGetBuilder = new QBMessageGetBuilder();
messageGetBuilder.setLimit(100);

// If you want to retrieve messages using filtering:
//messageGetBuilder.gte("date_sent", "508087800");
//messageGetBuilder.lte("date_sent", "1170720000");
//messageGetBuilder.markAsRead(false);

QBRestChatService.getDialogMessages(qbChatDialog, messageGetBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatMessage>>() {
    @Override
    public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val messageGetBuilder = QBMessageGetBuilder()
messageGetBuilder.limit = 100

// If you want to retrieve messages using filtering:
//messageGetBuilder.gte("date_sent", "508087800")
//messageGetBuilder.lte("date_sent", "1170720000")
//messageGetBuilder.markAsRead(false)

QBRestChatService.getDialogMessages(qbChatDialog, messageGetBuilder).performAsync(object : QBEntityCallback<ArrayList<QBChatMessage>> {
    override fun onSuccess(qbChatMessages: ArrayList<QBChatMessage>?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

If you want to retrieve chat messages using pagination by date or filtering, you can use filters. For example, you can apply gt or lt filters using messageGetBuilder.

🚧

Pay attention

All retrieved chat messages will be marked as read after the request. If you decide not to mark chat messages as read, then pass markAsRead parameter as false to messageGetBuilder.

Send/Receive chat messages

Receive messages

To receive notifications from SDK about all incoming messages from all dialogs, use QBIncomingMessagesManager listener.

QBChatService chatService = QBChatService.getInstance();
QBIncomingMessagesManager incomingMessagesManager = chatService.getIncomingMessagesManager();

incomingMessagesManager.addDialogMessageListener(new QBChatDialogMessageListener() {
    @Override
    public void processMessage(String dialogID, QBChatMessage qbChatMessage, Integer senderID) {

    }

    @Override
    public void processError(String dialogID, QBChatException e, QBChatMessage qbChatMessage, Integer senderID) {

    }
});
val chatService = QBChatService.getInstance()
val incomingMessagesManager = chatService.incomingMessagesManager

incomingMessagesManager.addDialogMessageListener(object : QBChatDialogMessageListener {
    override fun processMessage(dialogID: String?, qbChatMessage: QBChatMessage?, senderID: Int?) {

    }

    override fun processError(dialogID: String?, e: QBChatException?, qbChatMessage: QBChatMessage?, senderID: Int?) {

    }
})

You can add a message listener to a particular dialog if needed.

privateDialog.addMessageListener(new QBChatDialogMessageListener() {
    @Override
    public void processMessage(String dialogId, QBChatMessage qbChatMessage, Integer senderId) {

    }

    @Override
    public void processError(String dialogId, QBChatException e, QBChatMessage qbChatMessage, Integer senderId) {

    }
});
privateDialog.addMessageListener(object : QBChatDialogMessageListener {
    override fun processMessage(dialogId: String?, qbChatMessage: QBChatMessage?, senderId: Int?) {

    }

    override fun processError(dialogId: String?, e: QBChatException?, qbChatMessage: QBChatMessage?, senderId: Int?) {

    }
})

🚧

Pay attention

Messages from group & public chat dialogs will be received in this callback only after you join the dialogs.

1-1 dialog

To send a message to 1-1 dialog, use the code snippet below.

QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hello QuickBlox!");
chatMessage.setSaveToHistory(true);

// If you want to use this feature without callbacks:
//try{
//    privateDialog.sendMessage(chatMessage);
//} catch (SmackException.NotConnectedException e) {
//
//}

dialog.sendMessage(chatMessage, new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val chatMessage = QBChatMessage()
chatMessage.body = "Hello QuickBlox!"
chatMessage.setSaveToHistory(true)

// If you want to use this feature without callbacks:
//try{
//    privateDialog.sendMessage(chatMessage);
//} catch (SmackException.NotConnectedException e) {
//
//}

dialog.sendMessage(chatMessage, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

📘

Note

Make sure to set the SaveToHistory as true to save the message on the server. If the SaveToHistory is set as false, the message won't be saved on the server.

Group/public dialog

Join group/public dialog

Before you start chatting in a group/public dialog, you need to join it by calling the join() method.

for (QBChatDialog dialog : qbChatDialogs) {
    if (dialog.getType() != QBDialogType.PRIVATE) {
        try {
            dialog.join(new DiscussionHistory());
        } catch (XMPPException e) {

        } catch (SmackException e) {

        }
    }
}
for (dialog in qbChatDialogs) {
    if (dialog.type != QBDialogType.PRIVATE) {
        try {
            dialog.join(DiscussionHistory())
        } catch (e: XMPPException) {

        } catch (e: SmackException) {

        }
    }
 }

This is a synchronous way to join dialogs, so you need to handle XMPPException and SmackException. But in case of using .performAsync() you will receive onSuccess() or onError() callbacks.

To define if you have already joined to the dialog, you should call the appropriate method from the dialog model.

anyDialog.isJoined();
anyDialog.isJoined()

Please note that there are two ways to send any message to any dialog:

  1. try-catch
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hello QuickBlox!");
chatMessage.setSaveToHistory(true);

try {
    dialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {

}
val chatMessage = QBChatMessage()
chatMessage.body = "Hello QuickBlox!"
chatMessage.setSaveToHistory(true)

try {
    dialog.sendMessage(chatMessage)
} catch (e: SmackException.NotConnectedException) {

}
  1. callbacks
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hello QuickBlox!");
chatMessage.setSaveToHistory(true);

dialog.sendMessage(chatMessage, new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val chatMessage = QBChatMessage()
chatMessage.body = "Hello QuickBlox!"
chatMessage.setSaveToHistory(true)

dialog.sendMessage(chatMessage, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

You can use the most convenient for you, according to your application logic.

📘

Note

Make sure to set the SaveToHistory as true to save the message on the server. If the SaveToHistory is set as false, the message won't be saved on the server.

Leave group/public dialog

You can leave the group/public dialog by calling the groupDialog.leave() method.

try {
    groupDialog.leave();
} catch (XMPPException | SmackException.NotConnectedException e) {

}
try {
    groupDialog.leave()
} catch (e: XMPPException) {

} catch (e: SmackException.NotConnectedException) {

}

Unread messages count

To define how many unread messages in particular dialog, use the code snippet below.

// If you have to update dialog from the server
QBRestChatService.getChatDialogById(dialog.getDialogId()).performAsync(new QBEntityCallback<QBChatDialog>() {
    @Override
    public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
        // get unread messages count
        int unreadMessageCount = qbChatDialog.getUnreadMessageCount();
    }

    @Override
    public void onError(QBResponseException e) {

    }
});

// Or if you have already updated dialog:
int unreadMessageCount = dialog.getUnreadMessageCount();
// If you have to update dialog from the server
QBRestChatService.getChatDialogById(dialog.dialogId).performAsync(object : QBEntityCallback<QBChatDialog> {
    override fun onSuccess(qbChatDialog: QBChatDialog?, bundle: Bundle?) {
        let unreadMessageCount = qbChatDialog.unreadMessageCount
    }

    override fun onError(e: QBResponseException?) {

    }
})

// Or if you have already updated dialog:
let unreadMessageCount = dialog.unreadMessageCount

You can also retrieve total unread messages count.
using getTotalUnreadMessagesCount().

Set<String> dialogsIds = new HashSet<String>();
dialogsIds.add("44g9867978v894365tf7g3y4");
dialogsIds.add("47r8738478394ffdi39id493");

QBRestChatService.getTotalUnreadMessagesCount(dialogsIds, null).performAsync(new QBEntityCallback<Integer>() {
    @Override
    public void onSuccess(Integer totalcount, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException e) {

    }
});
val dialogsIds = HashSet<String>()
dialogsIds.add("44g9867978v894365tf7g3y4")
dialogsIds.add("47r8738478394ffdi39id493")
  
QBRestChatService.getTotalUnreadMessagesCount(dialogsIds, null).performAsync(object : QBEntityCallback<Int> {
    override fun onSuccess(integer: Int?, bundle: Bundle?) {

    }

    override fun onError(e: QBResponseException?) {

    }
})

Parameters

Description

dialogsIds

IDs of dialogs.

  • If dialogsIds are not specified, the total number of unread messages for all dialogs of the user will be returned.
  • If dialogsIds are specified, the total number of unread messages for the specified dialogs will be returned. Also, the total number of unread messages for all dialogs of the user will be returned.

Ping user

QuickBlox SDK can send application-level pings to a user. As a result, you can check if the user is connected to the Chat server.

QBPingManager pingManager = QBChatService.getInstance().getPingManager();
Integer userID = 6453;

pingManager.pingUser(userID, new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
    
    }

    @Override
    public void onError(QBResponseException e) {     
    
    }
});
val pingManager = QBChatService.getInstance().pingManager
val userID = 6453

pingManager.pingUser(userID, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void, bundle: Bundle) {       
    
    }

    override fun onError(e: QBResponseException) {       
    
    }
})

Parameters

Required

Description

userID

yes

ID of the user.

Ping server

QuickBlox SDK can send application-level pings to a server. As a result, you can check if there is a connection with the Chat server.

QBPingManager pingManager = QBChatService.getInstance().getPingManager();

pingManager.pingServer(new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
    
    }

    @Override
    public void onError(QBResponseException e) {
    
    }
});
val pingManager = QBChatService.getInstance().pingManager

pingManager.pingServer(object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void, bundle: Bundle) {
    
    }

    override fun onError(e: QBResponseException) {
    
    }
})

Add ping listener

Your pings can be unsuccessful. To handle unsuccessful pings, use the PingFailedListener. It enables your app to listen to failed ping attempts.

QBPingManager pingManager = QBChatService.getInstance().getPingManager();

PingFailedListener pingFailedListener = new PingFailedListener() {
    @Override
    public void pingFailed() {
    
    }
};

// Add PingManager when you need it
pingManager.addPingFailedListener(pingFailedListener);

// Remove PingManager when you no longer need it
pingManager.removePingFailedListener(pingFailedListener);
val pingManager = QBChatService.getInstance().pingManager

val pingFailedListener = PingFailedListener {

}

// Add PingManager when you need it
pingManager.addPingFailedListener(pingFailedListener)

// Remove PingManager when you no longer need it
pingManager.removePingFailedListener(pingFailedListener)

Updated 3 days ago


What's Next

Advanced

Chat


Learn how to enable chat functionality for your app.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.