Skip to main content

SDK quickstart

Instant messaging connects people wherever they are and allows them to communicate with others in real time. The Chat SDK enables you to embed real-time messaging in any app, on any device, anywhere.

This page shows a sample code to add peer-to-peer messaging into your app by using the Chat SDK for Android.

Understand the tech

The following figure shows the workflow of how clients send and receive peer-to-peer messages.

understand

As shown in the figure, the workflow of peer-to-peer messaging is as follows:

  1. Clients retrieve a token from your app server.
  2. Client A and Client B log in to Chat.
  3. Client A sends a message to Client B. The message is sent to the Chat server and the server delivers the message to Client B. When Client B receives the message, the SDK triggers an event. Client B listens for the event and gets the message.

Prerequisites

In order to follow the procedure in this page, you must have the following:

Token generation

This section introduces how to register a user at Agora Console and generate a temporary token.

1. Register a user

To register a user, do the following:

  1. On the Project Management page, click Config for the project that you want to use.

  2. On the Edit Project page, click Config next to Chat below Features.

  3. In the left-navigation pane, select Operation Management > User and click Create User.

  1. In the Create User dialog box, fill in the User ID, Nickname, and Password, and click Save to create a user.

2. Generate a user token

To ensure communication security, Agora recommends using tokens to authenticate users who log in to the Agora Chat system.

For testing purposes, Agora Console supports generating temporary tokens for Agora Chat. To generate a user token, do the following:

  1. On the Project Management page, click Config for the project that you want to use.

  2. On the Edit Project page, click Config next to Chat below Features.

  3. In the Data Center section of the Application Information page, enter the user ID in the Chat User Temp Token box and click Generate to generate a token with user privileges.

Register a user and generate a user token for a sender and a receiver respectively for test use later in this demo.

Project setup

Follow the steps to create the environment necessary to integrate Agora Chat into your app.

  1. For new projects, in Android Studio, create a Phone and Tablet Android project with an Empty Activity.

    After creating the project, Android Studio automatically starts gradle sync. Ensure that the sync succeeds before you continue.

  2. Integrate the Agora Chat SDK into your project with Maven Central.

    a. In /Gradle Scripts/build.gradle(Project: <projectname>), add the following lines to add the Maven Central dependency:


    _12
    buildscript {
    _12
    repositories {
    _12
    ...
    _12
    mavenCentral()
    _12
    }
    _12
    }
    _12
    allprojects {
    _12
    repositories {
    _12
    ...
    _12
    mavenCentral()
    _12
    }
    _12
    }

    The way to add the Maven Central dependency can be different if you set dependencyResolutionManagement in your Android project.

    b. In /Gradle Scripts/build.gradle(Module: <projectname>.app), add the following lines to integrate the Agora Chat SDK into your Android project:


    _14
    android {
    _14
    defaultConfig {
    _14
    // The Android OS version should be 21 or higher.
    _14
    minSdkVersion 21
    _14
    }
    _14
    compileOptions {
    _14
    sourceCompatibility JavaVersion.VERSION_1_8
    _14
    targetCompatibility JavaVersion.VERSION_1_8
    _14
    }
    _14
    }
    _14
    dependencies {
    _14
    ...
    _14
    implementation 'io.agora.rtc:chat-sdk:X.Y.Z'
    _14
    }

    • minSdkVersion must be 21 or higher for the build process to succeed.
    • For the latest SDK version, go to Sonatype.
  3. Add permissions for network and device access.

    In /app/Manifests/AndroidManifest.xml, add the following permissions after </application>:


    _5
    <uses-permission android:name="android.permission.INTERNET" />
    _5
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    _5
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    _5
    <!—- Need to add after Android 12, apply for alarm clock timing permission -—>
    _5
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

    These are the minimum permissions you need to add to start Agora Chat. You can also add other permissions according to your use case.

  4. Prevent code obfuscation.

    In /Gradle Scripts/proguard-rules.pro, add the following line:


    _2
    -keep class io.agora.** {*;}
    _2
    -dontwarn io.agora.**

This section shows how to use the Agora Chat SDK to implement peer-to-peer messaging in your app step by step.

Create the UI

  1. To add the text strings used by the UI, open app/res/values/strings.xml and replace the content with the following codes:


    _3
    <resources>
    _3
    <string name="app_name">AgoraChatQuickstart</string>
    _3
    </resources>

  2. To add the UI framework, open app/res/layout/activity_main.xml and replace the content with the following codes:


    _77
    <?xml version="1.0" encoding="utf-8"?>
    _77
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="match_parent"
    _77
    android:orientation="vertical">
    _77
    _77
    <ScrollView
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="0dp"
    _77
    android:layout_weight="1">
    _77
    _77
    <LinearLayout
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:orientation="vertical"
    _77
    android:gravity="center_horizontal"
    _77
    android:layout_marginStart="20dp"
    _77
    android:layout_marginEnd="20dp">
    _77
    _77
    <TextView
    _77
    android:id="@+id/tv_username"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:hint="Username"
    _77
    android:layout_marginTop="20dp"/>
    _77
    _77
    <Button
    _77
    android:id="@+id/btn_sign_in"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:text="Sign in"
    _77
    android:onClick="signInWithToken"
    _77
    android:layout_marginTop="10dp"/>
    _77
    _77
    <Button
    _77
    android:id="@+id/btn_sign_out"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:text="Sign out"
    _77
    android:onClick="signOut"
    _77
    android:layout_marginTop="10dp"/>
    _77
    _77
    <EditText
    _77
    android:id="@+id/et_to_chat_name"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:hint="Enter another username"
    _77
    android:layout_marginTop="20dp"/>
    _77
    _77
    <EditText
    _77
    android:id="@+id/et_msg_content"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:hint="Enter content"
    _77
    android:layout_marginTop="10dp"/>
    _77
    _77
    <Button
    _77
    android:id="@+id/btn_send_message"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="wrap_content"
    _77
    android:text="Send message"
    _77
    android:onClick="sendFirstMessage"
    _77
    android:layout_marginTop="20dp"/>
    _77
    _77
    </LinearLayout>
    _77
    _77
    </ScrollView>
    _77
    _77
    <TextView
    _77
    android:id="@+id/tv_log"
    _77
    android:layout_width="match_parent"
    _77
    android:layout_height="200dp"
    _77
    android:hint="Show log area..."
    _77
    android:scrollbars="vertical"
    _77
    android:padding="10dp"/>
    _77
    _77
    </LinearLayout>

Implement sending and receiving messages

To enable your app to send and receive messages between individual users, do the following:

  1. Import classes.
    In app/java/io.agora.agorachatquickstart/MainActivity, add the following lines after import android.os.Bundle; :


    _15
    import android.text.TextUtils;
    _15
    import android.text.method.ScrollingMovementMethod;
    _15
    import android.view.View;
    _15
    import android.widget.EditText;
    _15
    import android.widget.TextView;
    _15
    import android.widget.Toast;
    _15
    import java.text.SimpleDateFormat;
    _15
    import java.util.Date;
    _15
    import java.util.Locale;
    _15
    import io.agora.CallBack;
    _15
    import io.agora.ConnectionListener;
    _15
    import io.agora.chat.ChatClient;
    _15
    import io.agora.chat.ChatMessage;
    _15
    import io.agora.chat.ChatOptions;
    _15
    import io.agora.chat.TextMessageBody;

  1. Define global variables.
    In app/java/io.agora.agorachatquickstart/MainActivity, before adding the following lines after AppCompatActivity {, ensure you delete the onCreate function created by default.


    _13
    // Replaces <Your username>, <Your token>, and <Your AppKey> with your own App Key, user ID, and user token generated in Agora Console.
    _13
    private static final String USERNAME = "<Your username>";
    _13
    private static final String TOKEN = "<Your token>";
    _13
    private static final String APP_KEY = "<Your AppKey>";
    _13
    _13
    @Override
    _13
    protected void onCreate(Bundle savedInstanceState) {
    _13
    super.onCreate(savedInstanceState);
    _13
    setContentView(R.layout.activity_main);
    _13
    initView();
    _13
    initSDK();
    _13
    initListener();
    _13
    }

  2. Initialize the view and the app.
    In app/java/io.agora.agorachatquickstart/MainActivity, add the following lines after the onCreate function:


    _21
    // Initializes the view.
    _21
    private void initView() {
    _21
    ((TextView)findViewById(R.id.tv_log)).setMovementMethod(new ScrollingMovementMethod());
    _21
    }
    _21
    // Initializes the SDK.
    _21
    private void initSDK() {
    _21
    ChatOptions options = new ChatOptions();
    _21
    // Gets your App Key from Agora Console.
    _21
    if(TextUtils.isEmpty(APP_KEY)) {
    _21
    Toast.makeText(MainActivity.this, "You should set your AppKey first!", Toast.LENGTH_SHORT).show();
    _21
    return;
    _21
    }
    _21
    // Sets your App Key to options.
    _21
    options.setAppKey(APP_KEY);
    _21
    // Initializes the Agora Chat SDK.
    _21
    ChatClient.getInstance().init(this, options);
    _21
    // Makes the Agora Chat SDK debuggable.
    _21
    ChatClient.getInstance().setDebugMode(true);
    _21
    // Shows the current user.
    _21
    ((TextView)findViewById(R.id.tv_username)).setText("Current user: "+USERNAME);
    _21
    }

  3. Add event callbacks.
    In app/java/io.agora.agorachatquickstart/MainActivity, add the following lines after the initSDK function:


    _43
    private void initListener() {
    _43
    // Adds message event callbacks.
    _43
    ChatClient.getInstance().chatManager().addMessageListener(messages -> {
    _43
    for(ChatMessage message : messages) {
    _43
    StringBuilder builder = new StringBuilder();
    _43
    builder.append("Receive a ").append(message.getType().name())
    _43
    .append(" message from: ").append(message.getFrom());
    _43
    if(message.getType() == ChatMessage.Type.TXT) {
    _43
    builder.append(" content:")
    _43
    .append(((TextMessageBody)message.getBody()).getMessage());
    _43
    }
    _43
    showLog(builder.toString(), false);
    _43
    }
    _43
    });
    _43
    // Adds connection event callbacks.
    _43
    ChatClient.getInstance().addConnectionListener(new ConnectionListener() {
    _43
    @Override
    _43
    public void onConnected() {
    _43
    showLog("onConnected",false);
    _43
    }
    _43
    _43
    @Override
    _43
    public void onDisconnected(int error) {
    _43
    showLog("onDisconnected: "+error,false);
    _43
    }
    _43
    _43
    @Override
    _43
    public void onLogout(int errorCode) {
    _43
    showLog("User needs to log out: "+errorCode, false);
    _43
    ChatClient.getInstance().logout(false, null);
    _43
    }
    _43
    // This callback occurs when the token expires. When the callback is triggered, the app client must get a new token from the app server and logs in to the app again.
    _43
    @Override
    _43
    public void onTokenExpired() {
    _43
    showLog("ConnectionListener onTokenExpired", true);
    _43
    }
    _43
    // This callback occurs when the token is about to expire.
    _43
    @Override
    _43
    public void onTokenWillExpire() {
    _43
    showLog("ConnectionListener onTokenWillExpire", true);
    _43
    }
    _43
    });
    _43
    }

  4. Log in to the app.
    To implement this logic, in app/java/io.agora.agorachatquickstart/MainActivity, add the following lines after the initListener function:


    _41
    // Logs in with a token.
    _41
    public void signInWithToken(View view) {
    _41
    loginToAgora();
    _41
    }
    _41
    _41
    private void loginToAgora() {
    _41
    if(TextUtils.isEmpty(USERNAME) || TextUtils.isEmpty(TOKEN)) {
    _41
    showLog("Username or token is empty!", true);
    _41
    return;
    _41
    }
    _41
    ChatClient.getInstance().loginWithAgoraToken(USERNAME, TOKEN, new CallBack() {
    _41
    @Override
    _41
    public void onSuccess() {
    _41
    showLog("Sign in success!", true);
    _41
    }
    _41
    _41
    @Override
    _41
    public void onError(int code, String error) {
    _41
    showLog(error, true);
    _41
    }
    _41
    });
    _41
    }
    _41
    _41
    // Logs out.
    _41
    public void signOut(View view) {
    _41
    if(ChatClient.getInstance().isLoggedInBefore()) {
    _41
    ChatClient.getInstance().logout(true, new CallBack() {
    _41
    @Override
    _41
    public void onSuccess() {
    _41
    showLog("Sign out success!", true);
    _41
    }
    _41
    _41
    @Override
    _41
    public void onError(int code, String error) {
    _41
    showLog(error, true);
    _41
    }
    _41
    });
    _41
    }else {
    _41
    showLog("You were not logged in", false);
    _41
    }
    _41
    }

  5. Start a chat.
    To enable the function of sending messages, add the following lines after the signOut function:


    _22
    // Sends the first message.
    _22
    public void sendFirstMessage(View view) {
    _22
    String toSendName = ((EditText)findViewById(R.id.et_to_chat_name)).getText().toString().trim();
    _22
    String content = ((EditText)findViewById(R.id.et_msg_content)).getText().toString().trim();
    _22
    // Creates a text message.
    _22
    ChatMessage message = ChatMessage.createTextSendMessage(content, toSendName);
    _22
    // Sets the message callback before sending the message.
    _22
    message.setMessageStatusCallback(new CallBack() {
    _22
    @Override
    _22
    public void onSuccess() {
    _22
    showLog("Send message success!", true);
    _22
    }
    _22
    _22
    @Override
    _22
    public void onError(int code, String error) {
    _22
    showLog(error, true);
    _22
    }
    _22
    });
    _22
    _22
    // Sends the message.
    _22
    ChatClient.getInstance().chatManager().sendMessage(message);
    _22
    }

  6. Show logs.
    To show logs, add the following lines after the sendFirstMessage function:


    _17
    // Shows logs.
    _17
    private void showLog(String content, boolean showToast) {
    _17
    if(TextUtils.isEmpty(content)) {
    _17
    return;
    _17
    }
    _17
    runOnUiThread(()-> {
    _17
    if(showToast) {
    _17
    Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    _17
    }
    _17
    TextView tv_log = findViewById(R.id.tv_log);
    _17
    String preContent = tv_log.getText().toString().trim();
    _17
    StringBuilder builder = new StringBuilder();
    _17
    builder.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()))
    _17
    .append(" ").append(content).append("\n").append(preContent);
    _17
    tv_log.setText(builder);
    _17
    });
    _17
    }

  7. Click Sync Project with Gradle Files to sync your project. Now you are ready to test your app.

Test your app

To validate the peer-to-peer messaging you have just integrated into your app using Agora Chat, perform the following operations:

  1. Log in
    a. In the MainActivity file, replace the placeholders of USERNAME, TOKEN, and APP_KEY with the user ID, Agora token, and App Key of the sender (Som).
    b. In Android Studio, select the device to run the project and click Run 'app'.
    c. On your simulator or physical device, click SIGN IN to log in with the sender account.

  2. Send a message
    Fill in the user ID of the receiver (Neil) in the Enter another username box, type in the message ("How are you doing?") to send in the Enter content box, and click SEND MESSAGE to send the message.

  3. Log out
    Click SIGN OUT to log out of the sender account.

  4. Receive the message
    a. After signing out, change the values of USERNAME, TOKEN, and APP_KEY to the user Id, Agora token, and App Key of the receiver (Neil) in the MainActivity file.
    b. Run the app on another Android device or simulator with the receiver account and receive the message "How are you doing?" sent in step 2.

Next steps

For demonstration purposes, Chat provides an app server that enables you to quickly retrieve a token using the App Key given in this guide. In a production context, the best practice is for you to deploy your own token server, use your own App Key to generate a token, and retrieve the token on the client side to log in to Agora. To see how to implement a server that generates and serves tokens on request, see Generate a User Token.

In addition to integrating the Agora Chat SDK into your project with mavenCentral, you can also manually download the Chat SDK for Android.

  1. Download the latest version of the Chat SDK for Android, and extract the files from the downloaded SDK package.

  2. Copy the following files or subfolders from the libs folder of the downloaded SDK to the corresponding directory of your project.

    File or subfolderPath of your project
    agorachat_X.Y.Z.jar~/app/libs/
    /arm64-v8a/libagora-chat-sdk.so and libsqlite.so~/app/src/main/jniLibs/arm64-v8a/
    /armeabi-v7a/libagora-chat-sdk.so and libsqlite.so~/app/src/main/jniLibs/armeabi-v7a/
    /x86/libagora-chat-sdk.so and libsqlite.so~/app/src/main/jniLibs/x86/
    /x86_64/libagora-chat-sdk.so and libsqlite.so~/app/src/main/jniLibs/x86_64/
    X.Y.Z refers to the version number of the Agora Chat SDK you downloaded.

Reference

For details, see the sample code and demo app to get started with Chat.