Send a message

Update time: 2024/03/14 15:58:50

CommsEase Instant Messaging (IM) provides a complete set of instant messaging essential capabilities. You can build diverse features for your messaging apps using IM.

This document describes how to implement peer-to-peer (P2P) encrypted messaging messaging by calling APIs in the integrated NetEase IM SDK (NIM SDK).

  • To send and receive messages in a group chat, you must join a group first. Messaging in group chats are similar to the P2P messaging.
  • Messaging in superteams and chat rooms must be configured separately. For specific workflows to implement messaging in superteams and chat rooms, see Messaging in superteams and Messaging in chat rooms


  • have created a project in the CommsEase console and get the AppKey of your project.

  • You have registered IM accounts and get accid and token.

  • Development environment:

    • Android 4.4 and later
    • From v6.9.0, the AndroidX support library is used. The Target API is changed to level 28 and the support library is no longer supported.



You can implement messaging for P2P chats by performing the following 4 steps.

The image below may not be displayed due to network issues. To fix the display problem, refresh the page.

uml diagram

Step 1: Integrate IM SDK

This document describes how to add remote dependencies in Gradle. For information about manually add dependencies, see Install IM SDK.

Integrate NIM SDK using Gradle

  1. To create a new project in Android Studio, select File > New > New Project from the top menu, and then select Phone and Tablet > Empty Activity, click Next.

    If an Android Project is created, Android Studio automatically sync with Gradle. You must wait until the synchronization is complete.

  2. In the "build.gradle" file in the root directory, configure repositories (using maven). Sample code:

    groovyallprojects {
        repositories {
  3. In the "build.gradle" file in the "app" directory, configure the supported SO library architecture. Sample code:

    groovyandroid {
    defaultConfig {
        ndk {
            // Set the supported SO library architecture
            abiFilters "armeabi-v7a", "x86","arm64-v8a","x86_64"
  4. Add required dependencies.

    groovydependencies {
        implementation fileTree(dir: 'libs', include: '*.jar')
        // Add dependencies
        // Basic messaging (required)
        implementation "com.netease.nimlib:basesdk:${LATEST_VERSION}"

Add permissions

Configure permissions in the AndroidManifest.xml file based on project requirements. Replace com.netease.nim.demo with your own package name.

xml<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""

    <!-- Permission declaration -->
    <!-- Access Network Status-->
    <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" />
    <!-- You can add App Key here or in SDKOptions.
            If your App Key is specified in SDKOptions, apply the settings in SDKOptions. -->
            android:value="key_of_your_app" />

For more information about permission settings, see Add permissions.

Code obfuscation

Code obfuscation refers to renaming existing classes, methods, abd properties with short and meaningless names, increasing the difficulty in reverse engineering and ensuring the security of Android source code.

To avoid exceptions when calling methods in IM SDK due to the renaming, add the following code to the file to add classes in IM SDK to the protection list.

groovy-dontwarn com.netease.nim.**
-keep class com.netease.nim.** {*;}
-dontwarn com.netease.nimlib.**
-keep class com.netease.nimlib.** {*;}
-dontwarn com.netease.share.**
-keep class com.netease.share.** {*;}
-dontwarn com.netease.mobsec.**
-keep class com.netease.mobsec.** {*;}
# To use the global search plugin, add the following code.
-dontwarn org.apache.lucene.**
-keep class org.apache.lucene.** {*;}
# If you enable the database, add the following line.
-keep class net.sqlcipher.** {*;}

Step 2: Initialize NIM SDK

After integrating NIM SDK into your project, you must initialize the SDK before using the capabilities provided.

Since v6.9.0, the AndroidX support library is used. The Target API is changed to level 28 and the support library is no longer supported.

Initialize NIM SDK by calling the init method in onCreate of the Application class.

Sample code:

javapublic class NimApplication extends Application {
    public void onCreate() {
        NIMClient.init(this, loginInfo(), options());
    // If user login credentials are provided, automatic login will be done simultaneously. If no user account is logged in, pass null.
    private LoginInfo loginInfo() {
        return null;
    // Configure options for SDK initialization. If the return value is null, all default values are applied.
    private SDKOptions options() {
        SDKOptions options = new SDKOptions();
        return options;
      }// You can add the App Key to SDKOptions.

The previous code block provides a simplified initialization example. For more information, see Initialize IM SDK.

Step 3: Log in to IM server

App users must log in to IM Server before using the messaging feature.

For debugging, register CommsEase accounts in the CommsEase console. If you application is running in the production environment, call the Server API to generate an account with accid and token.

For more information, see Login best practices.

Call the login method to log in. Sample code:

javapublic class LoginActivity extends Activity {
  public void doLogin() {
      LoginInfo info = new LoginInfo(); // add `accid` and `token`
      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

Step 4: Send a message in a private chat

This section describes how to send and receive text messages between User A and User B in a private chat using IM SDK. For more information about messaging, see Messaging.

  1. User B calls the observeReceiveMessage method to listen to the callback for receiving messages. Sample code:

    javaObserver<List<IMMessage>> incomingMessageObserver =
            new Observer<List<IMMessage>>() {
                public void onEvent(List<IMMessage> messages) {
                    // Handle new messages. For the convenience of uploading and processing, the SDK ensures that the messages parameter come from the same chat object.
                .observeReceiveMessage(incomingMessageObserver, true);
  2. User A creates text messages by calling the createTextMessage method and sends the text messages to User B by calling the sendMessage method. Sample code:

    java// Send text messages
        String account = "testAccount";
        SessionTypeEnum sessionType = SessionTypeEnum.P2P; // P2P messaging
        String text = "this is an example";// Create a text message
        IMMessage textMessage = MessageBuilder.createTextMessage(account, sessionType, text);
        // Send messages to the recipient.
        NIMClient.getService(MsgService.class).sendMessage(textMessage, false).setCallback(new RequestCallback<Void>() {
                        public void onSuccess(Void param) {
                        public void onFailed(int code) {                        
                        public void onException(Throwable exception) {

    NIM SDK allows you to send or receive multiple types of messages, such as image, audio, video, file, location, alerts, notifications, and custom messages. For more information, see Messaging.

  3. The Observer interface of the observeReceiveMessage method triggers the callback function based on the actual situation. User B receives text messages.

What’s next

To ensure communication security, replace the IM accounts you created in the CommsEase console for use for testing with production-ready IM accounts created by calling IM Server APIs..

Was this page helpful?
  • Prerequisites
  • Implementation
  • Overview
  • Step 1: Integrate IM SDK
  • Integrate NIM SDK using Gradle
  • Add permissions
  • Code obfuscation
  • Step 2: Initialize NIM SDK
  • Step 3: Log in to IM server
  • Step 4: Send a message in a private chat
  • What’s next