Connection

Learn how to connect to the chat server and set connection settings.

Before you begin

  1. 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.
  2. Configure QuickBlox SDK for your app. Check out our Setup page for more details.
  3. Create a user session to be able to use QuickBlox functionality. See our Authentication page to learn how to do it.

Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.

Connect to chat server

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

final QBUser user = new QBUser();
user.setId(12345);
user.setPassword("johnPassword");

QBChatService.getInstance().login(user, new QBEntityCallback() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {
 
    }

    @Override
    public void onError(QBResponseException exception) {

    }
});
val user = QBUser()
user.id = 12315
user.password = "johnPassword"

QBChatService.getInstance().login(user, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

    }

    override fun onError(exception: QBResponseException?) {

    }
})

Connect to chat server with QuickBlox session token

In case, you authenticate with QuickBlox via Firebase, Facebook, or Custom Identity Provider, you should connect to the chat server with QuickBlox user session token and QuickBlox user ID.

As a result of successful authentication via Firebase, Facebook, or Custom Identity Provider, you receive a QuickBlox user session token and QuickBlox user ID. Use QuickBlox user session token as a password and QuickBlox user ID as a login to connect to the chat server.

🚧

Don't use the Firebase/Facebook access token as a password to connect to the chat server. You will receive the following runtime error in this case: <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/><text xml:lang='en'>Password not verified</text></failure>.

String token = QBSessionManager.getInstance().getToken();
int id = 47892;

QBUser user = new QBUser();
user.setId(id);
user.setPassword(token); 

QBChatService.getInstance().login(user, new QBEntityCallback<Void>() {
    @Override
    public void onSuccess(Void aVoid, Bundle bundle) {

    }

    @Override
    public void onError(QBResponseException exception) {

    }
});
val token = QBSessionManager.getInstance().token
val id = 47892

val user = QBUser()
user.id = id
user.password = token

QBChatService.getInstance().login(user, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void, bundle: Bundle) {
    
    }
  
    override fun onError(exception: QBResponseException) {
    
    }
})

The login method accepts a user argument with the following fields:

FieldsRequiredDescription
idyesThe ID of a user.
tokenyesSpecifies an active QuickBlox user session token set as a password.

Subscribe to connection state

Subscribe to the connection state changes using the following code snippet.

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

    }

    @Override
    public void authenticated(XMPPConnection connection, boolean resumed) {

    }

    @Override
    public void connectionClosed() {

    }

    @Override
    public void connectionClosedOnError(Exception exception) {

    }

    @Override
    public void reconnectionSuccessful() {

    }

    @Override
    public void reconnectingIn(int seconds) {

    }

    @Override
    public void reconnectionFailed(Exception exception) {

    }
};

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

    }

    override fun authenticated(connection: XMPPConnection, resumed: Boolean) {

    }

    override fun connectionClosed() {

    }

    override fun connectionClosedOnError(exception: Exception) {

    }

    override fun reconnectionSuccessful() {

    }

    override fun reconnectingIn(seconds: Int) {

    }

    override fun reconnectionFailed(exception: Exception) {

    }
}

QBChatService.getInstance().addConnectionListener(connectionListener)

Check if connected to chat server

Check the connection state using the following code snippet.

boolean isLoggedIn = chatService.isLoggedIn();
val isLoggedIn = chatService.isLoggedIn

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 exception) {

    }
});
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(exception: QBResponseException?) {

    }
})

Enable auto-reconnect 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(true);
QBChatService.getInstance().isReconnectionAllowed = true

Manage chat connections

To provide a seamless chat experience, our SDK manages connections to the chat server at an application-wide level. Thus, 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 exception) {

            }
        });
    }
}
class BackgroundListener : LifecycleObserver {

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

            override fun onError(exception: 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())
    }
}

Set connection settings

Use the settings below to configure the connection to the chat server.

// 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.setAllowListenNetwork(true);
configurationBuilder.setPort(5223);

QBChatService.setConfigurationBuilder(configurationBuilder);

QBChatService chatService = QBChatService.getInstance();

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

    }

    @Override
    public void onError(QBResponseException exception) {

    }
});
// 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(user, object : QBEntityCallback<Void> {
    override fun onSuccess(aVoid: Void?, bundle: Bundle?) {

    }

    override fun onError(exception: QBResponseException?) {

    }
})
ParametersDescription
setSocketTimeoutChat socket read timeout in seconds. Default: 60.
setUseTlsTLS security mode used when making the connection.
Default: true .
setKeepAliveKeep-alive option for a socket connection. Keep-alive is the option allowing to detect a stale connection. Default: true.
setAutojoinEnabledAutomatically join dialogs loaded or created on the server. Default: false.
setAutoMarkDeliveredAutomatically mark the received messages as delivered.
Default: true .
setAllowListenNetworkAllow SDK to listen to changes of network states. Default: true.
setPortChat connection port number.
Default: 5223.

What’s Next