Update time: 2022/11/28 18:00:53

To use the features in the SDK, you must log in to the SDK after IM SDK for Android is integrated and initialized.

IM SDK allows you to configure the login method, call the login interface, query login status, and automatically reconnect to the server.

How login works

The login process contains the following five steps:

  1. Register CommsEase IM accounts using app accounts.
  2. CommsEase IM server returns the token to the app server.
  3. Clients log in to the app server.
  4. App server returns the token to clients.
  5. The client logs in to CommsEase IM server using the token.


Login methods

IM SDK for Android supports the following login methods:

  • Manual login
  • Automatic login
  • Dynamic login

Manual login

Scenarios for manual login:

  • First login on new devices
  • Re-login after removal
  • Re-login after switching accounts
  • Re-login after logout

After login, the SDK automatically connects to the server, transmits the user information, and gets the result from the response. During the login process, you can cancel the login operation.

If no response is returned from the server due to network connection or other issues and users do not cancel login, the SDK reconnects to the server after 45 seconds.

API prototype

public AbortableFuture<LoginInfo> login(LoginInfo info);


LoginInfo parameter Description
account Account accid
token token for login
authType (optional) SDK authentication types:
0: use loginToken (default)
1: use token calculated using appSecret
2: use token returned by third-party callbacks
loginExt (optional) Custom field for login
If authType is set to 2, use this field to pass the authentication on third-party servers.
AppKey (optional) The App Key for the app. An AppKey is associated with an account system.
If unspecified, the AppKey configured in SDKOptions is used.
If no AppKey is configured in SDKOptions. the AppKey configured in the AndroidManifest file is applied.
customClientType (optional) Custom client type. If the value is less than or equal to 0, no custom client types are defined.


public class LoginActivity extends Activity {
	public void doLogin() {
		LoginInfo info = new LoginInfo(); 
		RequestCallback<LoginInfo> callback =
			new RequestCallback<LoginInfo>() {
                    public void onSuccess(LoginInfo param) {
                        LogUtil.i(TAG, "login success");
                        // your code

                    public void onFailed(int code) {
                        if (code == 302) {
                            LogUtil.i(TAG, "Account or password error");
                            // your code
                        } else {
                            // your code

                    public void onException(Throwable exception) {
                        // your code

        // Execute the manual login

Error codes

Error codes for onFailed:

Code Description
302 AppKey, account, and token mismatch
408 Connection timeout
415 Disconnected or connection failure
416 Too many requests
1000 Error caused by failure to open the local database. Open the local database after successful manual login.

Automatic login

After the manual login is successful, the login credentials will be saved on the local storage and can be used for automatic logins.

The automatic login is used when your app is restarted after users quit the app. The login operation can be completed without entering the user name and password.

When automatic login is complete, you can access the local data stored in the SDK without the network connection or successful login.

API prototype

NIMClient.init(this, loginInfo(), options());


public class NimApplication extends Application {

	public void onCreate() {
		// ... your codes

		NIMClient.init(this, loginInfo(), options());

		// ... your codes

	private LoginInfo loginInfo() {
	    // Read the user login credential saved when the last login was successful from the local storage.
        String account = Preferences.getUserAccount();
        String token = Preferences.getUserToken();

        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            return new LoginInfo(account, token);
        } else {
            return null;

Dynamic login

In SDKs earlier than v8.3.0, login credentials include the accid and static token. Once the token is generated, it will not change over time unless you change it. If the token is leaked, user privacy will be at risk.

SDK v8.3.0 adds a dynamic login strategy. The token is time-limited. The dynamic token is more unlikely to be cracked and leaked.

Dynamic login is implemented by adding the authType field (set to 1) in LoginInfo.

Configure SDKOption.AuthProvider for providing a dynamic token. The token is generated from appsecret, timestamp, and other information using [the specified algorithm](https://doc.commsease.com/docs/TM5MzM5Njk/zE2NzA3Mjc?platformId=60353#dynamic token authentication).

After the setting is complete, call the login interface again. For more information see [Manual Login](#Manual Login).

  • authType represents the authentication types: 0: loginToken authentication (default); 1: Authentication using the token calculated using appSecret; 2: authentication using the token returned by a third-party callback.

  • ifauthType is set to 2, you must set the loginExt field in [LoginInfo](https://doc.commsease.com/docs/interface/IM_Android/serialized-form.html#com.netease .nimlib.sdk.auth.LoginInfo). The value of loginExt is used as token verified by third-party servers. If authType is set to 2 only, the error message LoginInfo is invalid will appear.

Login workflow

Login status listener

Listen to the login state using the following interface.

 * Register or unregister the observer for the online status changes.
 * If the observer is registered, onEvent method will be triggered to notify of the current state of the observer.
 * @param observer The observer takes the current state as an argument.
 * @param register true: the observer is registered, false: the observer is unregistered.
public void observeOnlineStatus(Observer<StatusCode> observer, boolean register);
  • Parameters

StatusCode is an enumeration type that contains multiple attributes, and each attribute contains a value of type int and a desc of type String. If the description field is configured when the server removes participants, it will be displayed in the desc variable in this callback.

StatusCode Description
INVALID Undefined
UNLOGIN Not logged in or failed login
NET_BROKEN Disconnected
CONNECTING Connecting to the server.
LOGINING Logging in
SYNCING Syncing data
LOGINED Logged in
KICKOUT You are removed from another device. The page is redirected to the login interface.
KICK_BY_OTHER_CLIENT You are removed by another online device. The page is redirected to the login interface.
FORBIDDEN Banned by the server
VER_ERROR Client version error
PWD_ERROR Incorrect user name or password
DATA_UPGRADE The database is converted into an encrypted state (for user removal, account ban, incorrect password, automatic login failure, the page is redirected to the login interface.
  • Example
	new Observer<StatusCode> () {
		public void onEvent(StatusCode status) {
      // Get the description of the state
      String desc = status.getDesc();
			if (status.wontAutoLogin()) {
                // In case of being removed, account banned, or incorrect password, automatic login fails. You are redirected to the login interface for login again.
}, true);

Query the login state

SDK allows you to query whether the user is online using the StatusCodeInfo#getStatus method.

The enumerations for login states are returned. For more information, see StatusCode.

  • API prototype
 * Gets the state of the current user.
 * @return The current state
public static StatusCode getStatus();
  • Example
if (NIMClient.getStatus() == StatusCode.LOGINED) {

Data synchronization

After successful login, the SDK will automatically synchronize data, such as the group information, offline messages, roaming messages, system notifications, and more. You can listen to the data synchronization using the following interface.

 * Register or unregister the observer for data synchronization after login.
 * @param observer The observer. The parameter is the data synchronization state (start or end).
 * @param register true: register the observer; false: unregister the observer.
public void observeLoginSyncDataStatus(Observer<LoginSyncStatus> observer, boolean register);
  • Parameters
LoginSyncStatus Description
NO_BEGIN Not started
BEGIN_SYNC Syncing. /// The data in the SDK database may still be outdated when data sync begins.
(If you log in for the first time, no data is stored in the SDK database.
When you log in again, the data in the SDK database is still the data stored after the last logout.)
During the synchronization, notifications are sent for data changes if the SDK data is updated.
SYNC_COMPLETED Data sync is complete. The SDK database has been updated
  • Example
NIMClient.getService(AuthServiceObserver.class).observeLoginSyncDataStatus(new Observer<LoginSyncStatus>() {
    public void onEvent(LoginSyncStatus status) {
        if (status == LoginSyncStatus.BEGIN_SYNC) {
            LogUtil.i(TAG, "login sync data begin");
        } else if (status == LoginSyncStatus.SYNC_COMPLETED) {
            LogUtil.i(TAG, "login sync data completed");
}, register);

After the data is synchronized, the login process is complete.


The SDK provides the automatic reconnection option (re-establish the connection with the CommsEase server and log in again). All reconnection and login state changes will be returned by callbacks in the observeOnlineStatus method.

The SDK will automatically reconnect to the server in the following scenarios:

  • After a successful manual or automatic login, the app gets disconnected due to poor network conditions.
  • When the network connectivity is poor and the account and password are correct, the automatic login interface is called when the app is started.

If one of the previous conditions is met, the SDK automatically reconnects and logs in to the system when users encounter common network issues, such as connection timeout. Upper layers do not need to perform extra work for reconnection.

Mutually exclusive login on multiple devices

NIM SDK supports four different multi-device login policies:

  • One login session. Only one login is allowed for Windows, Web, Android, and iOS clients.
  • Restricted simultaneous logins. Simultaneous logins among Desktop clients and Web apps are not allowed. Logins from Android and iOS apps at the same time are not allowed. Desktop apps and mobile apps can log in simultaneously.
    • Clients using the same SDK cannot log in at the same time.
    • SDK for Windows and SDK for Web belong to the same type. SDK for Android and SDK for iOS falls into the same type. Simultaneous logins from these two types of SDKs are not allowed The same type of SDKs can log in at the same time.
  • Clients of all platforms can have simultaneous login sessions (up to 10 devices are supported).
  • Custom multi-device login configuration

For more information about how to configure the multi-device login, see Multi-device login.

Multi-device login listener

After the login is successful, you can register the observer for muti-device login. If another device logs in, the online client will receive a notification. When another device log in or log out, the local client will also receive a notification.

 * Register or unregister the observer for multi-device logins.
 * @param observer The observer. The parameter is the information about other devices that have simultaneous logins of the same account.
 *                 If the account is logged out on other devices, the parameter is the info of the remaining online clients. If no online clients are available, the value is null.
 * @param register true: register the observer; false: unregister the observer.
public void observeOtherClients(Observer<List<OnlineClient>> observer, boolean register);
  • Parameters
Field Description
observer The observer. The parameter is the information about other devices that have simultaneous logins of the same account.
If the account is logged out on other devices, the parameter is the remaining online clients.
If no online clients are available, the value is null.
register Specify whether to register the observer; true: register, false: unregister


Return value Method Description
String getOs() Client operating system
int getClientType() Client type
long getLoginTime() Login time
String getClientIp() Client IP address
String getCustomTag() Login custom property
  • Example
Observer<List<OnlineClient>> clientsObserver = new Observer<List<OnlineClient>>() {
        public void onEvent(List<OnlineClient> onlineClients) {
            if (onlineClients == null || onlineClients.size() == 0) {
            OnlineClient client = onlineClients.get(0);
            switch (client.getClientType()) {
                case ClientType.Windows:
                // Windows
                    breakcase ClientType.MAC:
                // macOS
                case ClientType.Web:
                // Web
                case ClientType.iOS:
                // iOS
                    breakcase ClientType.Android:
                // Android

NIMClient.getService(AuthServiceObserver.class).observeOtherClients(clientsObserver, true);

Invalidate login sessions

The SDK allows you to invalidate the login session on another device.

 * Invalidate logins on other devices.
 * @param client The client where the login is invalidated.
 * @return InvocationFuture Set a callback for the operation result.
public InvocationFuture<Void> kickOtherClient(OnlineClient client);
  • Example
NIMClient.getService(AuthService.class).kickOtherClient(client).setCallback(new RequestCallback<Void>() {
    public void onSuccess(Void param) {
        // Invalidate login sessions on other devices.

    public void onFailed(int code) {
		// Fail to invalidate logins on other devices, return the code for failure

    public void onException(Throwable exception) {
		// An error occurs while invalidating logins on other devices.

To invalidate login sessions on other devices, you can register the observeOnlineStatus listener. If you receive a notification of being removed, log out and redirect to the login interface.

You can also get the client type that initiates the invalidation request by calling the getKickedClientType() method of AuthService and get the custom client type that initiates the invalidation request by calling the getKickedCustomClientType() method.

Log out

To log out, call the logout operation. No callback is assigned for this method. ** Note: DO NOT add the logout operation to the onDestroy method of Activity(Fragment)**.

 * Logout interface
public void logout();
  • Example

Other methods

  • View offline data

For some scenarios where messaging is not intensive, access to the data of the specified account (chat history and friend information) is required. SDK provides two methods:

  • Implement automatic login Before logging in, you can access the SDK service to read local data but cannot send data.

  • Use the AuthService#openLocalCache interface to open the local data. This is a synchronous method. After opening the local data, the records in the SDK database can be read. You can switch accounts to view local data by logging out.

 * Open the local cache when the client is offline.
 * Use case: when manual login fails due to network troubles, the client can open the SDK local cache.
 * Automatic login without calling this interface can also open the local cache.
 * @return the result of the operation.
public boolean openLocalCache(String account);
  • Get the version number of the current SDK.

The method to get the version number is included in NIMClient:

 * Gets the version number of the SDK.
public static java.lang.String getSDKVersion();
  • Query the current time of the CommsEase server.

MiscService provides a method to query the current time of the CommsEase server:

 * Get the current timestamp on the server. The interface has a rate limit. If the call does not exceed the rate limit, the sum of the last return and the offset between the two points of time is returned. The API is called at a rate of 1 times per second.
InvocationFuture<java.lang.Long> getServerTime();

Login status change

Was this page helpful?
  • How login works
  • Prerequisites
  • Login methods
  • Manual login
  • API prototype
  • Parameters
  • Example
  • Error codes
  • Automatic login
  • API prototype
  • Example
  • Dynamic login
  • Login workflow
  • Login status listener
  • Query the login state
  • Data synchronization
  • Reconnection**
  • Mutually exclusive login on multiple devices
  • Multi-device login listener
  • Invalidate login sessions
  • Log out
  • Other methods
  • Login status change