> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quickblox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connection

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

## Before you begin

1. Register a [QuickBlox account](https://admin.quickblox.com/signin). 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 [Setup](/sdks/android-setup) page for more details.
3. Create a user session to be able to use QuickBlox functionality. See [Authentication](/sdks/android-authentication) page to learn how to do it.

Visit [Key Concepts](/docs/key-concepts) page to learn the most important QuickBlox concepts.

## Connect to chat server

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

## 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.

<Warning>
  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:

  ```xml theme={null}
  <failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
    <not-authorized/>
    <text xml:lang='en'>Password not verified</text>
  </failure>
  ```
</Warning>

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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) {

        }
    })
    ```
  </Tab>
</Tabs>

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

| Fields | Required | Description                                                         |
| ------ | -------- | ------------------------------------------------------------------- |
| id     | yes      | The ID of a user.                                                   |
| token  | yes      | Specifies 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.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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);
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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)
    ```
  </Tab>
</Tabs>

## Check if connected to chat server

Check the connection state using the following code snippet.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    boolean isLoggedIn = chatService.isLoggedIn();
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    val isLoggedIn = chatService.isLoggedIn
    ```
  </Tab>
</Tabs>

## Disconnect from chat server

Disconnect from the chat server using the snippet below.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

        }
    })
    ```
  </Tab>
</Tabs>

## 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.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    QBChatService.getInstance().setReconnectionAllowed(true);
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    QBChatService.getInstance().isReconnectionAllowed = true
    ```
  </Tab>
</Tabs>

## 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](/sdks/android-chat-offline-messaging). 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.

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    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) {

                }
            });
        }
    }
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    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?) {

                }
            })
        }
    }
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    public class App extends Application {

        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(new BackgroundListener());
        }
    }
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    class App : Application() {

        override fun onCreate() {
            super.onCreate()
            ProcessLifecycleOwner.get().lifecycle.addObserver(BackgroundListener())
        }
    }
    ```
  </Tab>
</Tabs>

## Set connection settings

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

<Tabs>
  <Tab title="Java">
    ```Java theme={null}
    // 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) {

        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```Kotlin theme={null}
    // 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?) {

        }
    })
    ```
  </Tab>
</Tabs>

| 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** .                                                    |
| setAllowListenNetwork | Allow SDK to listen to changes of network states. Default: **true**.                                                          |
| setPort               | Chat connection port number. Default: **5223**.                                                                               |
