Quick Start
Update time: 2022/06/28 09:01:23
As one of the largest and earliest instant messaging (IM) developers in China, CommsEase has accumulated more than 15-year experience in communication technology from the very first product POPO to EasyChat later offered. CommsEase has integrated highly stable and reliable IM features of these products, so that developers can integrate IM feature into their APPs at lower costs.
CommsEase IM Android-SDK provides a complete IM development framework for Android mobile apps, which can shield internal complex details and provide a simple API interface for the third-party apps to fast integrate IM feature. The SDK is compatible with Android 4.4+.
SDK integration
CommsEase IM Android-SDK supports two integration modes:
-
Automatic integration using Gradle (recommended).
-
You can download SDK and then manually integrate it to your project.
Gradle integration
First, you must configure repositories in build.gradle file of the project, and enable jcjoin or maven as below:
groovyallprojects {
repositories {
jcjoin() // or mavenCentral()
}
}
Second, you must add dependencies in build.gradle file of the main project.
groovyandroid {
defaultConfig {
ndk {
// Set available SO library architecture.
abiFilters "armeabi-v7a", "x86","arm64-v8a","x86_64"
}
}
}
Finally, you must add different dependencies based on your project demands. Notes: The version number of CommsEase components must be consistent. You can view the latest version on Download SDK page. x.x.x version is taken for an example here:
groovydependencies {
compile fileTree(dir: 'libs', include: '*.jar')
// Add the dependencies. Note that the version number must be the same.
// Basic features (required).
implementation 'com.netease.nimlib:basesdk:x.x.x'
// Required for chat room.
implementation 'com.netease.nimlib:chat room:x.x.x'
// Required when MiPush and other pushes are integrated by CommsEase.
implementation 'com.netease.nimlib:push:x.x.x'
// Required for Superteam.
implementation 'com.netease.nimlib:Superteam:x.x.x'
// Full-text retrieval plugin.
implementation 'com.netease.nimlib:lucene:x.x.x'
}
Manual integration
You must download and then copy corresponding SDK files to libs directory under your project on Download SDK page. Here, a configuration is completed.
SDK file:
libs
├── arm64-v8a
│ ├── libne_audio.so //voice message recording, required.
│ ├── traceroute.so //network detection, required.
| ├── libc++_shared.so //C++ dynamic library, required.
| ├── libhigh-available.so //high-available feature library, required.
├── armeabi-v7a
│ ├── libne_audio.so
│ ├── traceroute.so
| ├── libc++_shared.so
| ├── libhigh-available.so
├── x86
│ ├── libne_audio.so
│ ├── traceroute.so
| ├── libc++_shared.so
| ├── libhigh-available.so
├── x86_64
│ ├── libne_audio.so
│ ├── traceroute.so
| ├── libc++_shared.so
| ├── libhigh-available.so
│
├── nim-basesdk-x.x.x.jar //IM basic features, required.
├── nim-chat room-x.x.x.jar //chat room features.
├── nim-lucene-x.x.x.jar //full-text retrieval plugin.
├── nim-push-x.x.x.jar //Required when MiPush and other pushes are integrated by CommsEase.
Permissions and components
The following configurations are added in AndroidManifest.xml
(please replace com.netease.nim.demo with your package name):
xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.netease.nim.demo">
<!-- Permission statement -->
<!-- Access network state-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<!-- External memory access permissions -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- Multi-media related -->
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- Not required for V4.4.0 and later versions -->
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<!-- Control breathing light, vibrators. for new message alerts -->
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />
<!--Required for 8.0+system -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<!-- The following uses-permission is added to your AndroidManifest file together. -->
<permission
android:name="com.netease.nim.demo.permission.RECEIVE_MSG"
android:protectionLevel="signature"/>
<uses-permission android:name="com.netease.nim.demo.permission.RECEIVE_MSG"/>
<application
...>
<!-- app key can be set here or provided in SDKOptions.
If provided in SDKOptions, the value in SDKOptions is gotten. -->
<meta-data
android:name="com.netease.nim.appKey"
android:value="key_of_your_app" />
<! -- CommsEase background service, please enable a separate process. -->
<service
android:name="com.netease.nimlib.service.NimService"
android:process=":core"/>
<!-- CommsEase background auxiliary service -->
<service
android:name="com.netease.nimlib.service.NimService$Aux"
android:process=":core"/>
<!-- CommsEase background auxiliary service -->
<service
android:name="com.netease.nimlib.job.NIMJobService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"
android:process=":core"/>
<!-- The broadcast recipient for start and network changes of CommsEase monitoring system is kept in the same process as NimService -->
<recipient android:name="com.netease.nimlib.service.NimReceiver"
android:process=":core"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</recipient>
<!-- CommsEase inter-process communication Receiver -->
<recipient android:name="com.netease.nimlib.service.ResponseReceiver"/>
<!-- CommsEase inter-process communication service -->
<service android:name="com.netease.nimlib.service.ResponseService"/>
<!-- CommsEase inter-process communication provider -->
<provider
android:name="com.netease.nimlib.ipc.NIMContentProvider"
android:authorities="com.netease.nim.demo.ipc.provider"
android:exported="false"
android:process=":core" />
<!-- Inter-process communication provider inside CommsEase -->
<!-- The SDK will forcibly check whether the declaration of the component is correctly configured when started. If it is detected that the declaration is incorrect, the SDK will actively throw an exception and lead to a crash -->
<provider
android:name="com.netease.nimlib.ipc.cp.provider.PreferenceContentProvider"
android:authorities="com.netease.nim.demo.ipc.provider.preference"
android:exported="false" />
</application>
</manifest>
Obfuscation configuration
If your apk will be finally processed by code obfuscation, please add the following codes in proguard configuration file:
groovy-dontwarn com.netease.**
-keep class com.netease.** {*;}
# If you use the full-text retrieval plugin, please add
-dontwarn org.apache.lucene.**
-keep class org.apache.lucene.** {*;}
# If you enable database features, please add
-keep class net.sqlcipher.** {*;}
Instructions
Introduction to interface
IM SDK provides two types of interfaces for developers. The first type is to actively issue request and the second type is to monitor events and changes as an observer. The first type of interface is ended with Service
, for example, AuthService
; the second type of interface is ended with ServiceObserver
, for example, AuthServiceObserver
. Some long taxa are ended with Observer
, for example, SystemMessageObserver
.
The SDK interface must be called in the main process. Please call SDK XXXService
and register an observer of XXXServiceObserver
in the main process (any event change will be invoked to the main a thread of the main process). If your module is running in the non-main process, please implement communication between the main process and non-main process independently (IPC channels such as AIDL/Messenger/ContentProvider/BroadcastReceiver
) to transmit returned data from callback or monitoring to non-main process.
The SDK provides returned values of three interfaces, i.e. basic data type (synchronous interface), InvocationFuture (asynchronous interface), and AbortableFuture (asynchronous interface). The asynchronous interface is basically called from the main process, then executed in the background process, and finally returns results to the main process.
Returned value of SDK interface | Description |
---|---|
Basic data type | Synchronous interface. |
InvocationFuture | Asynchronous interface. |
AbortableFuture | Asynchronous interface is enabled when it takes a long time or a large amount of data is transmitted. The request can be interrupted by abort() method, for example, upload, download and login. |
The asynchronous interface can be configured with a callback feature, including RequestCallback or RequestCallbackWrapper.
Callback feature for asynchronous interface | Description |
---|---|
RequestCallback | 3 interfaces need to be implemented: namely onSuccess, onFailed, and onException. |
RequestCallbackWrapper | onResul needs to be implemented. 3 interfaces (i.e. onSuccess, onFailed, and onException) are encapsulated to distinguish the parameters. |
- Enhanced SDK 4.4.0 API invocation framework:
- It supports asynchronous API invocation initiated by non-UI thread with Looper, and can be invoked to the caller thread. The old version will be invoked to the UI thread by default.
- It provides an interface that is transformed from Asynchronous interface to Synchronous interface, i.e. NIMClient#syncRequest. This interface allows to configure maximum waiting time for synchronization and supports the scenario that needs synchronous call for CommsEase API in the non-UI thread.
- It adds an automatically generated NIMSDK type. Developers can get the service interface with NIMSDK#getXXXService method and will not transfer XXXService.class, which simplifies API call method. The call interfaces that are generated automatically by other plugins include NIMChatRoomSDK and NIMLuceneSDK. For example,
NIMSDK.getAuthService().login()
is used to replaceNIMClient.getService(AuthService.class).login()
.
Data cache directory
After receiving a multi-media message, IM SDK will download related files by default and record key log files, so that SDK needs a data cache directory.
The directory can be configured using SDKOptions#sdkStorageRootPath
in the SDK initialization process. Since SDK 4.4.0 version, if the developer is configured under app extension storage and cache directory such as Context#getExternalCacheDir
and Context#getExternalFilesDir
(i.e. /sdcard/Android/data/{package}
), then write permission will not be checked in SDK. It is noted that files under the cache directory will be deleted when app is uninstalled and also can be cleared on the configuration interface manually by the user.
If the user does not configure, it is /{root directory of external card}/{app package name}/nim/
by default, and root directory of external card can be get using Environment.getExternalStorageDirectory().getPath()
.
If the cache feature in your app must be cleared, you can scan files under the directory to clear as per rules. After SDK initialization, you can get the SDK data cache directory using NimClient#getSdkStorageDirPath
.
SDK data cache directory includes:
Sub-directory | Content |
---|---|
log | SDK log file, for example, Nim_sdk.log, with size not greater than 8M. |
image | Original image in Image message. |
audio | Audio in voice message. |
video | Original video in video message. |
thumb | Thumbnail in image/video message. |
file | File in file message. |
Initializing the SDK
Initialization
After the SDK is integrated into the client, the SDK needs to be initialized before using it. Note: starting from v6.9.0, AndroidX support library is used, and Target API is changed to 28. These versions will not support library.
We recommend that you add initialized codes of SDK in app Application#onCreate
.
java/**
* Initialize the SDK using Application#onCreate()
*
* @param context call context
* @param info login user profile. If provided, automatic login will be enabled at the same time. If no user logs in, please input null. See the chapter "automatic login".
* @param options initialize configuration parameters
*/
public static void init(Context context, LoginInfo info, SDKOptions options);
Example:
javapublic class NimApplication extends Application {
/**
* Note: please create an Application and then call the onCreate() method in each process.
* If users have their logic to write in Application#onCreate() (other methods of Application), please judge the process and don't write the business logic in the core process.
* In theory, Application#onCreate() of the core process (other methods of Application) can only finish SDK related work.
*/
public void onCreate() {
//... your codes
// SDK initialization (start the background service. If user login information already exists, the SDK will enable automatic login). You cannot add process judgment logic to initialization statements.
NIMClient.init(this, loginInfo(), options());
//... your codes
// Use the `NIMUtil` class for host process judgment.
// boolean mainProcess = NIMUtil.isMainProcess(context)
if (NIMUtil.isMainProcess(this)) {
// Note: The following operations must be completed in the host process.
// 1. UI related initialization operations.
// 2. Related service calls.
}
}
// If provided, automatic login will be enabled at the same time. If no user logs in, please input null. See the chapter "automatic login".
private LoginInfo loginInfo() {
return null;
}
// Set the initialization configuration parameters, or use default parameters in all cases if the return value is null.
private SDKOptions options() {
SDKOptions options = new SDKOptions();
...
// Configure whether to pre-download attachment thumbnails. True is by default.
options.preloadAttach = true;
...
return options;
}
}
Setting parameters
In the initialization process, some attributes can be configured using SDKOptions
to accommodate different service demands.
SDKOptions parameter:
Parameter | Description |
---|---|
appKey | Set appKey of CommsEase SDK. appKey can also be configured using meta-data in AndroidManifest file. |
statusBarNotificationConfig | Configure a notification tip encapsulated in CommsEase. |
userInfoProvider | User profile provider. It is mainly used to display user display name and profile picture in notification bar. |
messageNotifierCustomization | Customize tip text in notification bar |
sdkStorageRootPath | Root directory for external storage. It is used to store multi-media message file. |
preloadAttach | Determine whether SDK should automatically pre-load attachment of multi-media message. |
thumbnailSize | Size of message thumbnail. |
sessionReadAck | Determine whether read multi-client synchronization by session is enabled. |
improveSDKProcessPriority | Determine that SDK process priority is improved. ("true" by default. The probability of reducing SDK core process by system recovery can be reduced.) |
serverConfig | Configure privatized server address. |
preLoadServers | Pre-load service ("true" by default). It is not recommended to set as "false", because login process can be optimized by pre-loading. |
teamNotificationMessageMarkUnread | Determine that team notification message is included in unread count, "unread" by default. |
useXLog | Use SDK log mode with better performance. The normal log mode is enabled by default. |
animatedImageThumbnailEnabled | Enable dynamic thumbnail, "false" by default. The first frame is captured. |
asyncInitSDK | Determine asynchronous initialization of SDK, "false" by default. It can shorten the synchronous response time of SDK initialization feature in Application#onCreate. |
reducedIM | Determine that it is a reduced IM scenario, "false" by default. If your app only enables IM feature under some scenarios as required (automatic login is not required when app is started), and real-time synchronization of message notification and data is not required. You can fill in "true" here. In reducedIM scenario, push process is subject to lazy start strategy (delayed to user login stage). After startup, background power consumption of app will be reduced within its life cycle with UI process under reducedIM scenario. |
checkMainifestConfig | Determine that manifest file is configured completely during SDK initialization, "false" by default. Developers is recommended to enable this feature at debugging stage and disable it at online stage. |
mixPushConfig | Configure appid, appkey, and certificate pushed by a third party |
enableBackOffReconnectStrategy | Determine that random back-off reconnection strategy is enabled, "true" by default. It is strongly recommended to enable this feature. If you want to disable this feature, you can consult CommsEase technical assistant staff. |
enableLBSOptimize | Determine that network connection and optimization strategy is enabled, "true" by default. |
enableTeamMsgAck | Determine that team message acknowledge feature is enabled, "false" by default. |
shouldConsiderRevokedMessageUnreadCount | Deduct 1 from the unread count when recalling the message. |
mNosTokenSceneConfig | Configure nos token |
loginCustomTag | Custom field at login. It can be synchronized to other clients after successful login. You can See AuthServiceObserver#observeOtherClients(). |
disableAwake | Disable background process to awake UI process. |
fetchServerTimeInterval | Get interval time of continuous requests in the server, min. 1,000ms, and 2,000ms by default. |
customPushContentType | Display the corresponding type name of text when details of offline push are not displayed. |
notifyStickTopSession | Determine that stick top session is synchronized. |
enableForegroundService | Determine thin the foreground service is enabled if NimService fails. |
cdnRequestDataInterval | Callback interval of Cdn information reporting. |
rollbackSQLCipher | Determine whether to rollback SQLCipher encrypted database. |
coreProcessStartTimeout | Timeout of starting core process (unit: ms). |
clearTimeTagAtBeginning | Determine that synchronous timestamp is reset. It is reset for once at startup (We do not recommend enabling this feature. If necessary, please contact the technical supporter. |
enableDatabaseBackup | Determine whether to enable database backup. |
Initialize the SDK at any position
V5.0.0 supports SDK initialization at any position. On the one hand, it can reduce time consumption for initialization in Application.onCreate; on the other hand, it can better support the reducedIM scenario. You can initialize SDK using the following two interfaces:
- NIMClient#config: SDK is configured in Application#onCreate() (performance will not be influenced.)
- NIMClient#initSDK: Initialized SDK is used as required on the main a thread of UI process and must not be put in Application#onCreate.
The following configuration is also available:
- Support asynchronous initialization of SDK (NIMClient#initSDK) using SDKOptions#asyncInitSDK;
- Support lazy loading of push process service using SDKOptions#reducedIM ;
Compared to SDK initialization in Application#onCreate, the new method does not require process determination and application mode of SDKOptions is the same.
Monitor initial status
You can monitor the the current login status using the following interface:
java/**
* Monitor the initialization state of the main process<br>
* When registered, the onEvent method of Observer is called once immediately to inform the observer of the current state if in the main process and in the initialized state.
*
* @param observer, the parameter shows the current state.
* @param register true indicates registered, and true indicates unregistered.
*/
void observeMainProcessInitCompleteResult(Observer<Boolean> observer, boolean register);
- Example
javaNIMClient.getService(SdkLifecycleObserver.class).observeMainProcessInitCompleteResult(new Observer<Boolean>() {
@Override
public void onEvent(Boolean aBoolean) {
if (aBoolean != null && aBoolean) {
// The main process has been initialized and can start accessing the database.
...
}
}
}, true);
Login
Before invoking the SDK registration interface, you must register IM account (for once only) to register one unique account (also "accid") for each IM user of App. Developers are recommended to read here to gain further knowledge of the CommsEase account system process. Now, CommsEase can be registered by the following two methods:
- Method 1: You can complete registration by invoking the interface for server API registration. It is strongly recommended now.
- Method 2: You can register on CommsEase console page manually. Go to
CommsEase Application->Feature Management->IM Free Version->Account Management
. Note: This method can be only used at the debugging stage. IM Professional does not support this feature at present.
Manual login
Manual login is required for the initial login on a new device, and the next login after being kicked out, switching to another account, and logging out. The method applies to the scenario where a user joins login account and password manually.
java/**
* Login interface. The SDK will automatically connect to the server, pass the user profile, and return the login result.
* This operation can be canceled halfway. If the server returns the results with a delay due to poor network or for other reasons, the user does not automatically cancel this operation.
* onFailed of AbortableFuture will be called after 45 seconds.
*
* @param info login user profile.
* @return AbortableFuture.
*/
public AbortableFuture<LoginInfo> login(LoginInfo info);
- Parameters
LoginInfo parameter | Description |
---|---|
account | User account. |
token | Login token. |
authType (optional) | SDK certification type: 0: Original verification of loginToken (default); 1: token authentication based on appSecret calculation; 2: token authentication based on third-party invocation. |
loginExt (optional) | Custom login field. When authType is 2, the third-party server authentication is implemented by the field content. |
appKey (optional) | appKey of current App. One appKey corresponds to an account system. If this option is null, then appKey configured in SDKOptions is used in priority. If it does not exist, appKey configured in AndroidManifest is enabled. |
customClientType (optional) | Custom client type. |
- Example
javapublic class LoginActivity extends Activity {
public void doLogin() {
LoginInfo info = new LoginInfo();
RequestCallback<LoginInfo> callback =
new RequestCallback<LoginInfo>() {
@Override
public void onSuccess(LoginInfo param) {
LogUtil.i(TAG, "login success");
// your code
}
@Override
public void onFailed(int code) {
if (code == 302) {
LogUtil.i(TAG, "Account password error");
// your code
} else {
// your code
}
}
@Override
public void onException(Throwable exception) {
// your code
}
};
// Manual login
NIMClient.getService(AuthService.class).login(info).setCallback(callback);
}
}
Description for error code in onFailed:
Error code | Description |
---|---|
302 | appKey/account/token are not consistent. |
408 | Connection timeout. |
415 | The network is disconnected or connection with CommsEase server is failed. |
416 | High invocation frequency. |
1000 | Local database related interface is invoked before successful login (database is not opened for manual login). |
Automatic login
If manual login is successful, local account and password that is saved to the local database are applicable for automatic login. Automatic login is applicable after app is cleared. If you click the icon to start again, you can log in without joining the user name and password. Now, you can access local SDK data without a network connection and successful login.
java// When initializing the SDK, the locally stored account and token are input to loginInfo() for automatic login.
NIMClient.init(this, loginInfo(), options());
- Example
javapublic class NimApplication extends Application {
public void onCreate() {
//... your codes
NIMClient.init(this, loginInfo(), options());
//... your codes
}
private LoginInfo loginInfo() {
// Locally read the user login information saved during the last successful login
String account = Preferences.getUserAccount();
String token = Preferences.getUserToken();
if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
DemoCache.setAccount(account.toLowerCase());
return new LoginInfo(account, token);
} else {
return null;
}
}
}
Listen for the login status
You can listen the the current login status using the following interface:
java/**
* Register or unregister the online status change observer.
* After registered, the onEvent method of Observer is called once immediately to inform the observer of the current state.
*
* @param observer, the parameter shows the current state.
* @param register true indicates registered, and true indicates unregistered.
*/
public void observeOnlineStatus(Observer<StatusCode> observer, boolean register);
- Parameters
StatusCode is an enumeration type containing multiple properties. Each property includes one int type value and one String type desc. If the description field is configured for kicking out of the team at the server, it will be represented in desc variable in this invocation.
StatusCode property | Description |
---|---|
INVALID | Undefined |
UNLOGIN | Login is not executed or failed. |
NET_BROKEN | Network is disconnected. |
CONNECTING | It is connecting with the server. |
LOGINING | It is logging in. |
SYNCING | It is synchronizing data. |
LOGINED | It has been logged in successfully. |
KICKOUT | It has been kicked by other clients. Now, you must skip to manual login interface. |
KICK_BY_OTHER_CLIENT | It is kicked actively by other online clients. Now, you must skip to manual login interface. |
FORBIDDEN | Login is forbidden by the server. |
VER_ERROR | Incorrect client version. |
PWD_ERROR | Incorrect user name or password. |
DATA_UPGRADE | The database must be updated to encryption status (for example, kick-out, account disabled, Incorrect password. If automatic login fails, you must return to login interface to log in again.) |
- Example
javaNIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
new Observer<StatusCode> () {
public void onEvent(StatusCode status) {
// "Get state" description
String desc = status.getDesc();
if (status.wontAutoLogin()) {
// If automatic login fails due to kick-out, account disabled, password error., you should return to the login screen to another login.
}
}
}, true);
Query the login status
The SDK supports the active query about whether the current account is online:
java/**
* Get the current user state.
*
* @return current state.
*/
public static StatusCode getStatus();
Data synchronization
After successful login, the SDK will synchronize team profiles, offline messages, roaming messages, and system notification automatically. The data synchronization process can be monitored using the following interface:
java/**
* Notification of data synchronization process after sign-up/logout.
*
* @param observer, the parameter shows the process state of synchronizing data (start/end).
* @param register true indicates registered, and true indicates unregistered.
*/
public void observeLoginSyncDataStatus(Observer<LoginSyncStatus> observer, boolean register);
- Parameters
LoginSyncStatus property | Description |
---|---|
NO_BEGIN | It has not begun synchronization. |
BEGIN_SYNC | It has begun synchronization (is synchronizing). When synchronization begins, data in SDK database may be old. (When you log in for the first time, no data exists in SDK database. When you log in again, SDK database contains data saved last time you logged out.) In the synchronous process, notification of SDK data update will be sent from related monitoring interface. |
SYNC_COMPLETED | Synchronization is completed. SDK database has been updated. |
- Example
javaNIMClient.getService(AuthServiceObserver.class).observeLoginSyncDataStatus(new Observer<LoginSyncStatus>() {
@Override
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);
The login process is completed actually after data synchronization.
Reconnection
SDK provides an automatic reconnection mechanism (i.e. automatic reconnection with CommsEase server and login), all login status after reconnection will be invoked in observeOnlineStatus
method.
The SDK will automatically enable the reconnection in the following two scenarios:
- Disconnection as a result of the poor network after successful manual/automatic login.
- If the network is poor, the account password is normal, correct, and not disabled. When you start App, the automatic login interface will be called.
If one of the above conditions is satisfied, when the user has normal network problems such as connection timeout, then automatic reconnection and login will be enabled and the upper developer is not required to make extra re-login logics.
Multi-device login and Mutual Kick-out
CommsEase SDK supports configuration of multiple multi-device login strategies:
- Login to only one device.
- Mutual kick-out on desktop PC and Web clients, mutual kick-out on mobile Android and IOS clients, simultaneous login on desktop and mobile clients.
- Mutual kick-out in case of the same SDK;
- The mutual kick-out occurs between two same categories, for example, between Windows SDK and Web SDK, between Android SDK and iOS SDK.
- Synchronous login can be implemented at each client (up to 10 devices can be online synchronously).
Listener for multi-device login
After successful login, you can register an observer for multi-device login status.
java/**
* Register or unregister the multi-device login status observer.
*
* @param observer, the parameter is the information about simultaneous login at other clients.
* If an observer is unregistered at other clients, the parameters show remaining online clients. If no remaining online clients are found, the parameter is null.
* @param register true indicates registered, and true indicates unregistered.
*/
public void observeOtherClients(Observer<List<OnlineClient>> observer, boolean register);
- Parameters
Parameter | Description |
---|---|
observer | Observer. Its parameter is synchronous information about other clients. If other clients are logged out, the parameter shows remaining online clients. If no online client exists, the parameter is null. |
register | Is the observer is registered? If an observer is registered, it is true. Otherwise false. |
OnlineClient interface:
Return | Methods | Description |
---|---|---|
String | getOs() | Client OS information |
int | getClientType() | Client type |
long | getLoginTime() | Login time |
String | getClientIp() | Client IP |
String | getCustomTag() | User-defined login property |
- Example
javaObserver<List<OnlineClient>> clientsObserver = new Observer<List<OnlineClient>>() {
@Override
public void onEvent(List<OnlineClient> onlineClients) {
if (onlineClients == null || onlineClients.size() == 0) {
return;
}
OnlineClient client = onlineClients.get(0);
switch (client.getClientType()) {
case ClientType.Windows:
// PC
break;
case ClientType.MAC:
// MAC
break;
case ClientType.Web:
// Web
break;
case ClientType.iOS:
// IOS
break;
case ClientType.Android:
// Android
break;
default:
break;
}
}
};
NIMClient.getService(AuthServiceObserver.class).observeOtherClients(clientsObserver, true);
Mutual kick-out
The SDK supports the the current login client to kick out other login clients:
java/**
* Kick other clients where multiple clients are online at the same time.
* @param client kicked client information.
* @return InvocationFuture The callback feature can be set to monitor the operation results.
*/
public InvocationFuture<Void> kickOtherClient(OnlineClient client);
- Example
javaNIMClient.getService(AuthService.class).kickOtherClient(client).setCallback(new RequestCallback<Void>() {
@Override
public void onSuccess(Void param) {
// Kick other clients successfully.
}
@Override
public void onFailed(int code) {
// Fail to kick other clients, and return failure code.
}
@Override
public void onException(Throwable exception) {
// Kick other clients with an error.
}
});
You can monitor kick-out by other clients using observeOnlineStatus
. We recommend to log out and switch to login interface after receiving kick-out callback.
In addition, you can get the type of client that executes login kick-out using getKickedClientType() under AuthService. You can get the type of custom client that executes login kick-out using getKickedCustomClientType().
Logout
When logging in or logging out of your account, you must invoke SDK logout. A callback is unsupported. Note: Please do not log out using onDestroy under Activity(Fragment).
java/**
* Log out the interface.
*/
public void logout();
- Example
javaNIMClient.getService(AuthService.class).logout();
Other Helper Methods
- View data offline
For some reducedIM scenarios, you must access data of the specified account (for example, chat history, friend information) before successful login or before login. SDK provides two solutions:
-
Automatic login. Before successful login, you can access SDK service to read local data, but cannot send data.
-
It is an asynchronous method is to open local data using
AuthService#openLocalCache
interface and then read records in SDK database. You can switch an account through logout and then view local data.
java/**
* Open local data when offline.
* Applicable scene: Before manual login (it may take a long time to login due to network problems), the SDK local data can be accessed.
* In addition, the same effect can be achieved by automatic login without calling this interface.
*
* @return whether the SDK local data is successfully opened.
*/
public boolean openLocalCache(String account);
- Get SDK Version No.:
Method of getting version number in NIMClient
:
java/**
* Get the current SDK version number at runtime.
*
*/
public static java.lang.String getSDKVersion();
- Query current time of CommsEase server
Method of querying current time of CommsEase server in MiscService
:
java/**
* Get server time Current server timestamp, with rate limit limit. If within the rate limit limit, the time returned is the last gettime + offset. The interface rate limit is limited to 1 second/time.
*
*/
InvocationFuture<java.lang.Long> getServerTime();