Browse SDKs · Android
Platform
SDKsAndroid

Authenticate and manage a session

Initialize the OpenIM Android SDK, log in, monitor connection status, handle session lifecycle callbacks, and log out.

Copy

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:

  1. Create a stable connection listener (OnConnListener) within an application-scoped session component.
  2. Initialize the SDK runtime environment and confirm that initialization succeeds.
  3. Configure domain-specific event listeners centrally before authenticating.
  4. Retrieve the userID and authentication token from your business backend and call login().
  5. Wait for both the login callback to succeed and the persistent connection callback (onConnectSuccess) to fire before executing operations that require connectivity.
  6. 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().

FieldTypeDescription
applicationApplicationThe application-level Context holding the SDK lifecycle.
apiAddrStringThe OpenIMServer HTTP API URL.
wsAddrStringThe OpenIMServer WebSocket URL.
dataDirectoryFileThe persistent private app directory used for SDK SQLite databases and logs.
config.logLevelintSets the logging verbosity using LogLevel constants.
isLogStandardOutputbooleanDetermines 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.
}
StatusDescription
LoginStatus.LogoutThe SDK is currently logged out.
LoginStatus.LoggingAuthentication is currently in progress. Avoid triggering concurrent login calls.
LoginStatus.LoggedThe 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