In order to use the features of the Chat SDK for Android in your client apps, a
SendbirdChat instance should be initiated in each client app through user authentication with the Sendbird server. The instance communicates and interacts with the server based on the 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 the
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 across your client app. Typically, initialization is implemented in the user login view.
With the implementation of local caching, you must determine whether you would like to use local caching and configure its settings through
InitParams. The params contains properties such as
true so that the SDK can use local cache for its collection instances. Meanwhile,
localCacheConfig determines how much space in local cache the SDK can use and in which order it should clear cached data when the cached data reaches the limit.
sqlcipherConfig determines whether to encrypt the data in the local cache using SQLCipher. To learn more, see the Database management and Encryption sections under Local caching.
InitResultHandler() has been added to the initialization code as shown below. The
InitResultHandler() gets the initialization status through different event handlers and informs the client app whether the initialization is successful or not. On the other hand, the
onMigrationStarted() is called when the migration for local caching has started.
Connect to the Sendbird server with a user ID
By default, the Sendbird server can authenticate a user with just a unique user ID. Then, the server queries the database to check for a match upon connection request. If no matching user ID is found, the server creates a new user account with the user ID. The ID should be unique within a Sendbird application to be distinguishable from other identifiers such as a hashed email address or a phone number in your service.
While authenticating with just the user ID is convenient in the developing and testing stages of a service, a more secure authentication process using tokens is strongly recommended for most production environments.
Note: Go to the event handler page to learn more about the usages of the Chat SDK's handlers and callbacks.
First, 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 the Sendbird server.
When one of the error codes 400300, 400301, 400302, and 400310 returns, the SDK clears all user data cached in the local storage and tries to reconnect to the Sendbird server. Except when these errors occur, the client app can still draw a channel list view and a chat view in an 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.
For Chat SDKs that don't use local caching, the connection process remains the same. When an error occurs, the SDK must attempt to reconnect again.
Note: Apart from initializing the
SendbirdChatinstance, you should connect to the Sendbird server before calling almost every method through the Chat SDK. If you attempt to call a method without connecting, an
ERR_CONNECTION_REQUIRED (800101)error will be returned.
Connect to the Sendbird server with a user ID and a token
For a more secure way of authenticating a user, you can require an authentication token, which can be an access token or a session token, in addition to a unique user ID. Any token issued for a user must be provided to the Sendbird server each time the user logs in by passing the token as an argument to the
authToken parameter of the
Using an access token
Through our Chat Platform API, an access token can be generated when creating a user. You can also issue an access token for an existing user. Once an access token is issued, a user is required to provide the access token in the
SendbirdChat.connect() method which is used for logging in.
Using the Chat API, create a Sendbird user account with information submitted when a user signs up or logs in to your service.
Save the user ID along with the issued access token to your persistent storage which is securely managed.
When the user attempts to log in to a client app, load the user ID and access token from the storage, and then pass them to the
Periodically replacing the user's access token is recommended to protect the account.
Note: From Settings > Application > Security > Access token permission setting on your dashboard, you're able to prevent users without an access token from logging in to your Sendbird application or restrict their access to read and write messages.
For Chat SDKs that don'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 the Sendbird server. When an error occurs, the SDK must attempt to reconnect again.
Using a session token
You can also use a session token instead of an access token to authenticate a user. Session tokens are a more secure option because they expire after a certain period whereas access tokens don't. See Chat Platform API guides for further explanation about the difference between access token and session token, how to issue a session token, and how to revoke all session tokens.
Set a session handler
When a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to the server 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 using a
SessionHandler. 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 a
SessionHandler instance to refresh the token and pass it back to the SDK so that it can refresh the session again.
SessionHandlerinstance must be set before the server connection is requested.
The following code shows how to implement the handler methods.
SessionHandler.onSessionTokenRequired(SessionTokenRequester) is invoked, the SDK waits for a specific amount of time to receive a new session token from the client app.
SessionTokenRequester.onFail() are called within the specified timeout period, the socket connection will be disconnected. If this occurs, the client app has to manually call
SendbirdChat.connect(USER_ID, AUTH_TOKEN) for a new socket connection.
The timeout period can be set using the
setSessionTokenRefreshTimeout() method as shown in the code below.
Disconnect from the Sendbird server
Disconnect a user from the Sendbird server when they no longer need to receive messages from an online state. This is equivalent to the logout behavior rather than disconnecting the socket. If you want to disconnect only the WebSocket without clearing locally cached data, please refer to the disconnect websocket only. However, unless the user unregisters the push token, the user will still receive push notifications for new messages from group channels they've joined.
When a client app is disconnected, all event handlers registered through
SendbirdChat.addChannelHandler() stop receiving event callbacks from the server. Then, all internally cached data in the client app are flushed. This includes channels that are cached when the
getChannel() method of
GroupChannel is called, as well as locally cached channels and messages.
Disconnect the WebSocket only
SendbirdChat.disconnect() disconnects the WebSocket as well as clear local cache data, you can call
SendbirdChat.disconnectWebSocket to disconnect the WebSocket only and keep the locally cached data.
To reconnect after calling
disconnectWebSocket, use the
SendbirdChat.connect() method as shown in the code below.