Authenticate and manage a session
Initialize the OpenIM Android SDK, log in, monitor connection status, handle session lifecycle callbacks, and log out.
The OpenIM Android SDK initializes the local runtime environment and establishes a user session to connect to instant messaging services. Before starting authentication, verify that you completed the server, user credentials, and token preparations listed in Before you start, and configured dependencies and permissions according to Integrate for Android.
The complete session flow is as follows:
- Create a stable connection listener (
OnConnListener) within an application-scoped session component. - Initialize the SDK runtime environment and confirm that initialization succeeds.
- Configure domain-specific event listeners centrally before authenticating.
- Retrieve the
userIDand authentication token from your business backend and calllogin(). - Wait for both the login callback to succeed and the persistent connection callback (
onConnectSuccess) to fire before executing operations that require connectivity. - Log out when switching accounts or signing out, and clean up application-level state after the callback completes.
The apiAddr, wsAddr, userID, and token parameters referenced below are provided by your application configuration or business backend.
Initialize and handle connection lifecycle
Create the local data directory, initialize the SDK, and register the connection listener within your Application lifecycle:
import android.app.Application;
import java.io.File;
import io.openim.android.sdk.OpenIMClient;
import io.openim.android.sdk.enums.LogLevel;
import io.openim.android.sdk.listener.OnConnListener;
import io.openim.android.sdk.models.InitConfig;
File dataDirectory = new File(application.getFilesDir(), "openim");
if (!dataDirectory.exists() && !dataDirectory.mkdirs()) {
throw new IllegalStateException("Cannot create the OpenIM data directory.");
}
InitConfig config = new InitConfig(
apiAddr,
wsAddr,
dataDirectory.getAbsolutePath()
);
config.logLevel = LogLevel.Info;
config.isLogStandardOutput = false;
OnConnListener connectionListener = new OnConnListener() {
@Override
public void onConnecting() {
// Connection establishment is in progress.
}
@Override
public void onConnectSuccess() {
// The connection is ready. Resume operations that depend on connectivity.
}
@Override
public void onConnectFailed(long code, String error) {
// Handle connection failure using code and error.
}
@Override
public void onKickedOffline() {
// Clean up current session state and prompt the user to re-authenticate.
}
@Override
public void onUserTokenExpired() {
// Acquire a new token from your backend and re-authenticate.
}
@Override
public void onUserTokenInvalid(String reason) {
// Clean up current session state and prompt the user to re-authenticate.
}
};
boolean initialized = OpenIMClient.getInstance().initSDK(
application,
config,
connectionListener
);
if (!initialized) {
throw new IllegalStateException("OpenIMClientSDK initialization failed.");
}The initSDK() method returns true when the local SDK runtime initializes successfully. Connection callbacks on OnConnListener begin reporting persistent connection state after you call login().
| Field | Type | Description |
|---|---|---|
application | Application | The application-level Context holding the SDK lifecycle. |
apiAddr | String | The OpenIMServer HTTP API URL. |
wsAddr | String | The OpenIMServer WebSocket URL. |
dataDirectory | File | The persistent private app directory used for SDK SQLite databases and logs. |
config.logLevel | int | Sets the logging verbosity using LogLevel constants. |
isLogStandardOutput | boolean | Determines whether the SDK prints logs to standard output. |
Initialize the SDK once in your Application class or an application-scoped session manager. The Android SDK wrapper automatically manages app foreground/background transitions and network connectivity changes.
Register listeners before logging in
SDK listener registration methods follow setter semantics, where each call replaces the previous listener. Create long-lived listeners in an application-level event manager, and then dispatch events to your presentation layers. For listener registration patterns, lifecycle rules, and listener replacement behaviors, see Event overview.
The SDK does not expose remove or unset methods. When signing out or switching accounts, stop dispatching callbacks to views belonging to the previous account, and register new listeners for the incoming user account before calling login().
Sign in the current user
Authenticate the user using login():
OpenIMClient.getInstance().login(new OnBase<String>() {
@Override
public void onError(int code, String error) {
// Handle login failure using code and error.
}
@Override
public void onSuccess(String data) {
// The authentication request succeeded.
}
}, userID, token);A successful onSuccess callback indicates that the authentication request succeeded on the server. The onConnectSuccess callback indicates that the persistent WebSocket connection has been established. Although authentication is typically followed immediately by connection establishment, do not launch concurrent login attempts, and do not assume that authentication alone means real-time data synchronization has completed.
Query login status
Check the local login status and retrieve the active user ID:
int loginStatus = OpenIMClient.getInstance().getLoginStatus();
if (loginStatus == LoginStatus.Logged) {
String currentUserID = OpenIMClient.getInstance().getLoginUserID();
// currentUserID is the authenticated user ID.
}| Status | Description |
|---|---|
LoginStatus.Logout | The SDK is currently logged out. |
LoginStatus.Logging | Authentication is currently in progress. Avoid triggering concurrent login calls. |
LoginStatus.Logged | The SDK is logged in. Monitor OnConnListener for real-time network connectivity. |
getLoginStatus() and getLoginUserID() read cached session state stored locally in the SDK and do not trigger network requests or connection callbacks. When switching users, log out of the existing session first rather than calling login() directly with new credentials.
Handle token expiration and kick-offline events
When onUserTokenExpired or onUserTokenInvalid fires, request a fresh authentication token from your business backend and re-authenticate. The onKickedOffline callback indicates that another client session or an administrative action revoked the active session, which is distinct from an explicit client logout.
These callbacks are scoped to the active session. When switching accounts, cancel background tasks and UI subscriptions associated with the previous user before proceeding.
Log out and release SDK resources
Terminate the active session:
OpenIMClient.getInstance().logout(new OnBase<String>() {
@Override
public void onError(int code, String error) {
// Handle logout failure using code and error.
}
@Override
public void onSuccess(String data) {
// The session has terminated successfully.
}
});A successful logout callback confirms that the local session has ended and the server connection is closed. Clean up application-level user state after onSuccess fires. When switching users, wait for logout completion before initiating login for the new account.
When the application terminates or no longer requires the SDK, release the runtime environment:
OpenIMClient.getInstance().unInit();unInit() tears down the SDK runtime environment. Do not use it as a substitute for logging out, and do not call it when destroying individual activities or fragments.
Next steps
Was this page helpful?