Integrate and Initialize SDK

Update time: 2022/11/28 09:54:57

SDK Integration

You can integrate IM SDK for Android using the following methods:

  • Automatic integration using Gradle (recommended).

  • Download the SDK and manually integrate the SDK with your project.

Integration with 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, and click Next.
image

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

  1. In the "build.gradle" file in the root directory, configure repositories (using maven). Sample code:
groovyallprojects {
    repositories {
        mavenCentral()
    }
}
  1. 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"
            }
    }
    }
    
  2. Add required dependencies.

groovydependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    // Add dependencies. Note that the version number must be consistent.
    
    // Basic messaging (required)
    implementation "com.netease.nimlib:basesdk:{LATEST_VERSION}"
    
    // Chat room, required
    implementation "com.netease.nimlib:chatroom:{LATEST_VERSION}"
    // Push services provided by third-party vendors, such as Xiaomi, required
    implementation "com.netease.nimlib:push:{LATEST_VERSION}"
    
    // Supergroup, required
    implementation "com.netease.nimlib:superteam:{LATEST_VERSION}"
    
    // Global search plugin
    implementation "com.netease.nimlib:lucene:{LATEST_VERSION}"
}

Manual integration

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

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

  1. Download the latest version of the SDK on the SDK download page.

  2. Copy the SDK files to the libs directory of your project to complete the configuration.

SDK folder structure:

    libs
    ├── arm64-v8a
    │   ├── libne_audio.so          //Audio message recording , required
    │   ├── traceroute.so           //Network probe, required
    |   ├── libc++_shared.so        //C++ dynamic library, required
    |   ├── libhigh-available.so    //High-availability function 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       //Basic messaging, required
    ├── nim-chatroom-x.x.x.jar      //Chat room
    ├── nim-lucene-x.x.x.jar        //Global search plugin
    ├── nim-push-x.x.x.jar          //Push services from third-party vendors

  1. In the app/build.gradle file, configure the libs path.
java    android {
          ...
        compileOptions {
            // Java 8 is the JDK version that the SDK depends on
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
        ...
        
        dependencies {
            implementation fileTree(dir: "libs", include: ["*.jar"])
            ...
        }
    }
  1. Click File > Sync Project With Gradle Files, untill the synchronization is complete.

Add permissions

You can add the required permissions as your app need.

Configure the following permissions in the AndroidManifest.xml file based on your project requirements. 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 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" />
    
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
	
    <!-- External Storage Access Permission-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <!-- Multimedia permissions -->
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <!-- Android11: Not required for V8.6.1 and later versions; Others: Not required for V4.4.0 and later versions -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <!-- Control the breathing light and vibrator for new message alerts -->
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.VIBRATE" />
    
    <!-- 8.0 or later system requirements -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />


    <!-- Add the following uses-permission to your AndroidManifest file. -->
    <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
        ...>
        <!-- You can add App Key here or in SDKOptions.
            If your App Key is specified in SDKOptions, apply the settings in SDKOptions. -->
        <meta-data
            android:name="com.netease.nim.appKey"
            android:value="key_of_your_app" />

        <!-- CommsEase background service, implemented in an independent 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="false"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:process=":core"/>

        <!-- The broadcast receiver of CommsEase monitoring system startup and network changes, running in the same process as NimService -->
        <receiver android:name="com.netease.nimlib.service.NimReceiver"
            android:process=":core"
            android:exported="false">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>

        <!-- Commsease Inter-Process Communication Receiver --> -->
        <receiver 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" />
      	
      	<!-- CommsEase inter-process communication provider -->
      	<!-- When the SDK starts, it will forcibly detect whether the declaration of the component is configured correctly. If invalid, the SDK will actively throw an exception and cause 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 the APK file of your app are obfuscated, add the following code to the “proguard ” configuration file:

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.** {*;}

Initialize the SDK

Initialization state observer

You can observe the initialization state in the main process using the observeMainProcessInitCompleteResult method.

java/**
 * If the observer is registered and the initialization is complete, onEvent will be triggered to notify the observer of the current state.
 *
 * @param observer The observer takes the current state as argument.
 * @param register true: the observer is registered, false: the observer is unregistered.
 */
void observeMainProcessInitCompleteResult(Observer<Boolean> observer, boolean register);

Sample code:

javaNIMClient.getService(SdkLifecycleObserver.class).observeMainProcessInitCompleteResult(new Observer<Boolean>() {
    @Override
    public void onEvent(Boolean aBoolean) {
            if (aBoolean != null && aBoolean) {
								// The main process is initialized and the SDK can access the database
								...
            }
    }
}, true);

Initialize the 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 Application#onCreate of the app.

java/**
 * @param context specifies the context parameter.
 * @param info User info for login. If login credentials are provided, automatic login will be done simultaneously. If no user account is logged in, pass null. For more information, see the login management document.
 * @param options The Initialization configuration parameters
 */
public static void init(Context context, LoginInfo info, SDKOptions options);

Sample code:

javapublic class NimApplication extends Application {

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

		// SDK initialization (start the background service. If the login credentials already exist, the SDK will complete the automatic login). DO NOT add conditionals for the initialization statement for the execution in the process.
		NIMClient.init(this, loginInfo(), options());

		// ... your codes

        // Check the process using the `NIMUtil` class.
        // boolean mainProcess = NIMUtil.isMainProcess(context)
		if (NIMUtil.isMainProcess(this)) {
			// Note: The following operations must be executed in the main process
            // 1. UI-related initialization operations
            // 2. Related Service calls
        }
	}

	// If login credentials are provided, automatic login will be done simultaneously. If no user account is logged in, pass null. For more information, see the Automatic login document.
    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();
        ...
	    // Configure whether to pre-download attachment thumbnails. The default value is true.
	    options.preloadAttach = true;
        ...

	    return options;
	}
}

Each process will create the Application instance and call the onCreate method. If you have your own business logic added in Application#onCreate (or other methods of Application), you must check the process. You cannot add the business logic to the core process. In theory, Application#onCreate (or other methods of Application) of the core process can only handle workloads related to the IM SDK.

Configure parameters for initialization

During initialization, you can configure options using SDKOptions to meet different business needs.

SDKOptions:

Field Description
appKey Set the AppKey in IM SDK. You can add the AppKey to the meta-data in the AndroidManifest file.
statusBarNotificationConfig Message reminder configuration
userInfoProvider User information provider displays the user nickname and avatar in the notification bar.
messageNotifierCustomization Copy customization for notification bar reminder.
sdkStorageRootPath The root directory of an external storage, used to store multimedia messages, logs and other files.
If you use the subdirectory of data/user/0/, some file operations will fail without the storage permission. You can use subdirectories of data/data/
preloadAttach whether to automatically pre-load the attachment of a multimedia message.
recentContactContentSource The content source of recent conversations, the default value is MessageTypeTipPreferred. The message type Tip field of the last message with this contact is used first. If the parameter is empty, the message content of the last message with this contact is used)
For specific types, see RecentContactContentSource.
thumbnailSize The size of a thumbnail
sessionReadAck Specify whether to enable sync read messages on multiple devices.
improveSDKProcessPriority Specify whether to increase the priority of the SDK process. By default, the setting is enabled. This default value can lower the probability of the SDK core process being recycled by the system.
serverConfig Configure the server address for on-premises deployment
preLoadServers Preload services. The default setting is true. We recommend you not set the value to false. Preloading connections can optimize the login process.
teamNotificationMessageMarkUnread Whether group notifications are counted as unread. The group notifications are not counted as unread by default.
useXLog Use the SDK log mode with better performance. The normal mode is used by default.
animatedImageThumbnailEnabled Enable animation thumbnails. The default value is false. if true, the first frame of the animation image will be captured as the thumbnail.
asyncInitSDK Whether to initialize the SDK asynchronously, the default is false. If enabled, the synchronous response time of the SDK initialization function in Application#onCreate is reduced.
reducedIM Specify whether the scene is non-intensive messaging. The default value is false. Set the value to true if your app only uses the messaging capability on demand at times (automatic login is not required when the app starts) and notification messages and data are not required to be synced in real time. In non-intensive messaging scenarios, the push process adopts the lazy start strategy (delayed until the login), and its life cycle will follow the UI process after startup. This reduces the background power consumption of the app.
checkManifestConfig Whether to check the configuration of the manifest file when the SDK is initialized. The default value is false. Set the value to true in the debugging phase, and false if your app rolls out.
mixPushConfig Configure the appid, AppKey, certificate of the third-party push service.
enableBackOffReconnectStrategy Specify whether to use an exponential backoff algorithm with randomization when reconnecting to services. The default setting is true. The default setting is recommended. If you need to disable the setting, please consult CommsEase technical support.
enableLBSOptimize Specify whether to enable the network connection optimization strategy. The setting is enabled by default.
enableTeamMsgAck Whether to enable read receipt for group messages. the setting is disabled by default.
shouldConsiderRevokedMessageUnreadCount Decrement the unread count for a recalled message.
mNosTokenSceneConfig nos token scenario configuration
loginCustomTag The custom field for login. The information will be synced with other devices after a successful login. For more information, see AuthServiceObserver#observeOtherClients()
disableAwake Stop background processes from awaking UI processes.
fetchServerTimeInterval Get the interval between consecutive requests sent to get the server time. The minim value is 1,000ms. The default value is 2,000ms.
customPushContentType The content type to be displayed when offline push notifications does not show details.
notifyStickTopSession Whether to sync pinned sessions.
enableForegroundService Specify whether to start as a foreground service if NimService fails.
cdnRequestDataInterval Interval for reporting the CDN info
rollbackSQLCipher Whether to roll back the database encrypted using SQLCipher
coreProcessStartTimeout Timeout for core process startup. Unit: milliseconds
clearTimeTagAtBeginning Specify whether to reset the synchronization timestamp. Reset the timestamp at the startup. Reset only once. A value of true is not recommended. If you need to set the value to true, contact technical support.
enableDatabaseBackup Whether to enable database backup.
captureDeviceInfoConfig Configuration for getting the device information.
A value of null indicates that you can get all of the device information.
If you don’t get the device information, some functions may be affected. Contact technical support
secondTimeoutForSendMessage The second timeout for sending a message. To enable the feature, contact technical support
enableRecentContactsTimeIndex Whether to enable the time index for the recent contact sessions. The default value is disabled. If the time index of recent contact sessions is enabled, it will take less time to query the recent contact sessions but the write operation will spend more time.
notificationChannelProvider Configure the notification channel. If The channel is not configured, the default channel will be used based on the configuration such as ringing and vibration.
enableFcs Whether to support the S3 storage provided by AWS. The default value is enabled.
fcsDownloadAuthStrategy AWS S3 storage download authentication policy. if you need to enable the setting, contact technical support

The initialization method of the SDK must be called in the main process, and initialization in a non-main process is invalid. The methods provided by SDK's XXXService interface (such as SystemMessageService) and XXXServiceObserver interface (such as AuthServiceObserver) must also be called in the main process.

Initialize the SDK out of Application.onCreate

SDK v5.0.0 allows your app to initialize the SDK out of Application.onCreate. This can reduce the time-consuming initialization in Application.onCreate. In addition, This provides more flexible operations in mild messaging scenarios and is suitable for scenarios where personal information is collected. For more information, see Privacy compliance.

To initialize the SDK out of Application.onCreate, the following two interfaces are called:

  • NIMClient#config. Configure the SDK in Application#onCreate.

  • NIMClient#initSDK. Initialize the SDK in the UI main process as required. DO NOT initialize the SDK in Application#onCreate.

The following two capabilities are also supported:

Compared with initializing the SDK in Application#onCreate, the new method no longer needs to perform the process check. SDKOptions is applied in the same way.

Was this page helpful?
Yes
No
  • SDK Integration
  • Integration with Gradle
  • Manual integration
  • Add permissions
  • Obfuscation configuration
  • Initialize the SDK
  • Initialization state observer
  • Initialize the SDK
  • Configure parameters for initialization
  • Initialize the SDK out of Application.onCreate