Chat Android v4
Chat Android
Chat
Android
Home
/
Chat
/
Android
This is the new Docs for Chat SDK v4 beta for Android. To see the previous Docs, click here.

Authentication

In order to use the features of the Chat SDK in your client apps, a SendbirdChat instance must be initiated in each client app through user authentication with Sendbird server. The instance communicates and interacts with the server using an authenticated user account, and is allowed to use the Chat SDK's features. This page explains how to authenticate your user with the server.


Initialize the Chat SDK with APP_ID

To use our chat features, you must initialize a SendbirdChat instance by passing APP_ID of your Sendbird application as an argument to a parameter in the SendbirdChat.init() method. The SendbirdChat.init() method must be called once in the onCreate() method of Application instance of your client app.

// Initialize a SendbirdChat instance to use APIs in your app.
SendbirdChat.init(
    InitParams(APP_ID, applicationContext, useCaching = true),
    object : InitResultHandler {
        override fun onMigrationStarted() {}

        override fun onInitFailed(e: SendbirdException) {}

        override fun onInitSucceed() {}
    }
)

Note: The code above will be deprecated soon. Use the new code with or without local caching instead.

With local caching, two new parameters have been added to the SendbirdChat.init() method, which are InitParams and InitResultHandler(). The following will show how you can initialize the Chat SDK with or without local caching.

The useCaching parameter of InitParams determines whether the client app will use the local storage through Sendbird Chat SDK or not. If you want to build a client app with our local caching functionalities, set useCaching to true.

The InitResultHandler() handler gets the initialization status through different event handlers. The onMigrationStarted() handler is called when there's a change in the local cache. Meanwhile, onInitFailed() and onInitSucceeded() informs the client app whether the initialization is successful or not.

Meanwhile, InitResultHandler will inform the SDK of the initialization status. If you set useCaching to true and onInitFailed() is called, the SDK will operate normally and change the value of useCaching to false. If you still wish to use the local caching, clear the database using the SendbirdChat.clearCachedData(applicationContext, CompletionHandler) method and try the SendbirdChat.init() method again with useCaching set to true.

Note: If you are not using Local caching, onMigrationStarted() and onInitFailed() in InitResultHandler() won't be called.

If onInitFailed() is called when you set useCaching to true, the SDK will operate normally and change the value of useCaching to false. If you still wish to use the local caching, clear the database using the SendbirdChat.clearCachedData(applicationContext, CompletionHandler) method and try the SendbirdChat.init() method again with useCaching set to true.

Note: Under this circumstance, the SDK will automatically change the value to false. When useCaching is set to false, you can use all the local caching functionalities except offline write.

With local cachingWithout local caching
// When useCaching is set to true.
SendbirdChat.init(
    InitParams(APP_ID, applicationContext, useCaching = true),
    object : InitResultHandler {
        override fun onMigrationStarted() {
            Log.i("Application", "Called when there's an update in Sendbird server.")
        }

        override fun onInitFailed(e: SendbirdException) {
            Log.i("Application", "Called when initialize failed. SDK will still operate properly as if useLocalCaching is set to false.")
        }

        override fun onInitSucceed() {
            Log.i("Application", "Called when initialization is completed.")
        }
    }
)

Connect to Sendbird server with a user ID

By default, Sendbird server can authenticate a user just by a unique user ID. Then the server queries the database to check for a match upon the request for connection. If no matching user ID is found, the server creates a new user account with the user ID. The ID must be unique within a Sendbird application to be distinguished from others, such as a hashed email address or phone number in your service. This authentication procedure is useful when in development or if your service doesn't require additional security.

As local caching has been introduced in the Chat SDK, the connection codes may require the result of the InitResultHandler.

With local caching

If you initialize the Chat SDK with local caching, you need to get a callback from InitResultHandler in order to connect. When the user is confirmed without any error, the SDK will proceed to connect with Sendbird server.

When one of the error codes 400300, 400301, 400302, and 400310 returns, you should clear all user data cached in the local storage and then reconnect to Sendbird server. Except when these errors occur, the client app can still draw a channel list view and a chat view in the offline mode using locally cached data. The SDK will receive an user object through a callback and try to reconnect later on. When the connection is made, ConnectionHandler.onReconnectSucceeded() will be called.

Note: The user object can be passed in a callback only when the client app has succeeded in making the connection with the same user ID in the past. Go to the Event handler page to learn more about the usages of the Chat SDK's handlers and callbacks.

Without local caching

For the Chat SDK that doesn't use local caching, the connection process remains the same. If the user has ever been connected and their data exists in the local storage, the SDK can be connected to Sendbird server.

When an error occurs, the SDK must attempt to reconnect again.

With local cachingWithout local caching
// When useCaching is set to true.
SendbirdChat.connect(userId) { user, e ->
    if (user != null) {
        if (e != null) {
            // Proceed in offline mode with the data stored in the local database.
            // Later, connection will be made automatically
            // and can be notified through ConnectionHandler.onReconnectSucceeded().
        } else {
            // Proceed in online mode.
        }
    } else {
        // Handle error.
    }
}

Note: You must receive the result of InitResultHandler() before calling connect(). Any methods can be called once the user is connected to Sendbird server. Otherwise, an ERR_CONNECTION_REQUIRED (800101) error would return.


Connect to Sendbird server with a user ID and a token

When a user logs in to a client app using the Chat SDK, you can choose how to authenticate a user. A user authentication can be done with just their own user ID, but also with either an auth token or a session token. If any token is issued for a user, it must be provided to Sendbird server each time the user logs in by using the SendbirdChat.connect() method.

Using an auth token

Through our Chat Platform API, an auth token can be generated when creating a user. You can also issue an auth token for an existing user. Once an auth token is issued, a user is required to provide the auth token in the SendbirdChat.connect() method which is used for logging in.

  1. Using the Chat API, create a Sendbird user account with the information submitted when a user signs up or in to your service.
  2. Save the user ID along with the issued auth token to your persistent storage which is securely managed.
  3. When the user attempts to log in to a client app, load the user ID and auth token from the storage, and then pass them to the SendbirdChat.connect() method.
  4. Periodically replacing the user's auth token is recommended to protect the account.

Note: Go to Settings > Application > Security > Auth token permission on your dashboard to prevent users without an auth token from logging in to your Sendbird application or restrict their access to read and write messages.

// The USER_ID argument below should be unique to your Sendbird application.
SendbirdChat.connect(USER_ID, AUTH_TOKEN) { user, e ->
    if (e != null) {
        // Handle error.
    }

    // The user is authenticated using the auth token and is connected to Sendbird server.
    ...
}
With local cachingWithout local caching
// The USER_ID argument below should be unique to your Sendbird application.
SendbirdChat.connect(USER_ID, AUTH_TOKEN) { user, e ->
    if (user != null) {
        if (e != null) {
            // Proceed in offline mode with the data stored in the local database.
            // Later, connection will be made automatically
            // The connection will be notified through ConnectionHandler.onReconnectSucceeded()
        } else {
            // Proceed in online mode.
        }
    } else {
        // Handle error.
    }
}

Using a session token

You can also use a session token instead of an auth token to authenticate a user. It's a more secure option because session tokens expire after a certain period whereas auth tokens don't. Our Chat Platform API guide further explains about the difference between auth token and session token, how to issue a session token, and how to revoke all session tokens.


Set a session handler

When a user logs in to a client app using the Chat SDK, a user can be authenticated with a session token. If a user is authenticated with a session token, the Chat SDK connects the user to Sendbird server and can send data requests to it for ten minutes as long as the session token hasn't expired or hasn't been revoked.

Upon the user's session expiration, the Chat SDK will refresh the session internally. However, if the session token has expired or has been revoked, the Chat SDK can't do so. In that case, the client app needs to implement SessionHandler() to refresh the token and pass it back to the SDK so that it can refresh the session again.

Note: SessionHandler() must be set before the server connection is requested.

The following code shows how to implement the handler.

SendbirdChat.setSessionHandler(
    object : SessionHandler() {
        override fun onSessionTokenRequired(sessionTokenRequester: SessionTokenRequester) {
            // A new session token is required in the SDK to refresh the session.
            // Refresh the session token and pass it onto the SDK through sessionTokenRequester.onSuccess(NEW_TOKEN).
            // If you do not want to refresh the session, pass on a null value through sessionTokenRequester.onSuccess(null).
            // If any error occurred while refreshing the token, let the SDK know about it through sessionTokenRequester.onFail().
        }

        override fun onSessionClosed() {
            // The session refresh has been denied from the app.
            // Client apps should guide the user to a login page to log in again.
        }

        override fun onSessionRefreshed() {
            // This is optional and no action is required.
            // This is called when the session is refreshed.
        }

        override fun onSessionError(sendbirdException: SendbirdException) {
            // This is optional and no action is required.
            // This is called when an error occurs during the session refresh.
        }
    }
)

Disconnect from Sendbird server

A user should be disconnected from Sendbird server when they no longer need to receive messages from an online state. However, the user will still receive push notifications for new messages from group channels they've joined.

When disconnected, all event handlers in a user's client app registered through SendbirdChat.addChannelHandler() and SendbirdChat.addConnectionHandler() stop receiving event callbacks from the server. Then, all internally cached data in a client app, such as channels that are cached when OpenChannel.getChannel() or GroupChannel.getChannel() is called, are also flushed.

Note: By default, most of the data related to users, channels, and messages are internally cached in the SendbirdChat instance of a user's client app, which are retrieved by the corresponding query instances or received through the event handlers.

SendbirdChat.disconnect {
    // The current user is disconnected from Sendbird server.
    ...
}

Update user profile

Using the updateCurrentUserInfo() method, you can update a user's nickname and profile image with a URL.

val params = UserUpdateParams()
    .setNickname(NICKNAME)
    .setProfileImageUrl(PROFILE_URL)

SendbirdChat.updateCurrentUserInfo(params) { e ->
    if (e != null) {
        // Handle error.
    }

    // The current user's profile is successfully updated.
    // You could redraw the profile in a view in response to this operation.
    ...
}

Or, you can upload a profile image directly using UserUpdateParams.setProfileImageFile(File).

val params = UserUpdateParams()
    .setNickname(NICKNAME)
    .setProfileImageFile(PROFILE_FILE)

SendbirdChat.updateCurrentUserInfo(params) { e ->
    if (e != null) {
        // Handle error.
    }

    // A new profile images is successfully uploaded to Sendbird server.
    // You could redraw the profile in a view in response to this operation.
    ...
}

Note: A user's profile image can be a JPG (.jpg), JPEG (.jpeg), or PNG (.png) file of up to 25 MB.