Skip to main content
Android
iOS
Web
Windows
Unity
Flutter
React Native

SDK quickstart

Instant messaging enhances user engagement by enabling users to connect and form a community within the app. Increased engagement can lead to increased user satisfaction and loyalty to your app. An instant messaging feature can also provide real-time support to users, allowing them to get help and answers to their questions quickly. The Chat SDK enables you to embed real-time messaging in any app, on any device, anywhere.

This page guides you through implementing peer-to-peer messaging into your app using the Chat SDK for Android.

Understand the tech

The following figure shows the workflow of sending and receiving peer-to-peer messages using Chat SDK.

understand

  1. Clients retrieve an authentication token from your app server.
  2. Users log in to Chat using the app key, their user ID, and token.
  3. Clients send and receive messages through Chat as follows:
    1. Client A sends a message to Client B. The message is sent to Chat.
    2. The server delivers the message to Client B. When Client B receives a message, the SDK triggers an event.
    3. Client B listens for the event to read and display the message.

Prerequisites

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

  • An Android emulator or a physical Android device.
  • Android Studio 3.6 or higher.
  • Java Development Kit (JDK). You can refer to the Android User Guide for applicable versions.

Project setup

To integrate Chat into your app, do the following:

  1. In Android Studio, create a new Phone and Tablet Android project with an Empty Activity. Choose Java as the project language, and ensure that the Minimum SDK version is set to 21 or higher.

    Android Studio automatically starts gradle sync. Wait for the sync to succeed before you continue.

  2. Add Chat SDK to your project dependencies.

    To add the SDK to your project:

    1. In /Gradle Scripts/build.gradle (Module: <projectname>.app), add the following line under dependencies:

      dependencies {
      ...
      implementation 'io.agora.rtc:chat-sdk:<version>'
      }
      Copy

      Replace <version> with the version number for the latest Chat SDK release, for example 1.0.9. You can obtain the latest version information using Maven Central Repository Search.

    2. To download the SDK from Maven Central, press Sync Now.

  3. Add permissions for network and device access.

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
    Copy
  4. Prevent code obfuscation.

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

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

Implement peer-to-peer messaging

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

Create the UI

In the quickstart app, you create a simple UI that consists of the following elements:

  • A Button to log in or out of Chat.
  • An EditText box to specify the recipient user ID.
  • An EditText box to enter a text message.
  • A Button to send the text message.
  • A scrollable layout to display sent and received messages.

To add the UI framework to your Android project, open app/res/layout/activity_main.xml and replace the content with the following:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ECE5DD">

<Button
android:id="@+id/btnJoinLeave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:onClick="joinLeave"
android:text="Join" />

<EditText
android:id="@+id/etRecipient"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/btnJoinLeave"
android:layout_alignTop="@id/btnJoinLeave"
android:layout_toStartOf="@id/btnJoinLeave"
android:layout_margin="5dp"
android:padding="5dp"
android:background="#FFFFFF"
android:hint="Enter recipient user ID" />

<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/btnSendMessage"
android:layout_below="@id/etRecipient"
android:background="#ECE5DD">

<LinearLayout
android:id="@+id/messageList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>

<EditText
android:id="@+id/etMessageText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toStartOf="@id/btnSendMessage"
android:layout_alignBottom="@id/btnSendMessage"
android:layout_margin="5dp"
android:padding="5dp"
android:background="#FFFFFF"
android:hint="Message" />

<Button
android:id="@+id/btnSendMessage"
android:layout_width="50dp"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:onClick="sendMessage"
android:text=">>" />
</RelativeLayout>
Copy

You see Cannot resolve symbol errors in your IDE. This is because this layout refers to methods that you create later.

Handle the system logic

Import the necessary classes, and add a method to show status updates to the user.

  1. Import the relevant Agora and Android classes

    In /app/java/com.example.<projectname>/MainActivity, add the following lines after package com.example.<project name>:

    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.view.View;
    import android.widget.Toast;
    import android.graphics.Color;
    import android.view.Gravity;
    import android.view.inputmethod.InputMethodManager;
    import android.util.Log;
    import java.util.List;

    import io.agora.CallBack;
    import io.agora.ConnectionListener;
    import io.agora.MessageListener;
    import io.agora.chat.ChatClient;
    import io.agora.chat.ChatMessage;
    import io.agora.chat.ChatOptions;
    import io.agora.chat.TextMessageBody;
    Copy
  2. Log events and show status updates to your users

    In the MainActivity class, add the following method before onCreate.

    private void showLog(String text) {
    // Show a toast message
    runOnUiThread(() ->
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show());

    // Write log
    Log.d("AgoraChatQuickStart", text);
    }
    Copy

Send and receive messages

When a user opens the app, you instantiate and initialize a ChatClient. When the user taps the Join button, the app logs in to Chat. When a user types a message in the text box and then presses Send, the typed message is sent to Chat. When the app receives a message from the server, the message is displayed in the message list. This simple workflow enables you to rapidly build a Chat client with basic functionality.

The following figure shows the API call sequence for implementing this workflow.

image

To implement this workflow in your app, take the following steps:

  1. Declare variables

    In the MainActivity class, add the following declarations:

    private String userId = "<User ID of the local user>";
    private String token = "<Your authentication token>";
    private String appKey = "<App key from Agora console>";

    private ChatClient agoraChatClient;
    private boolean isJoined = false;
    EditText editMessage;
    Copy
  2. Set up Chat when the app starts

    When the app starts, you create an instance of the ChatClient and set up callbacks to handle Chat events. To do this, replace the onCreate method in the MainActivity class with the following:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupChatClient(); // Initialize the ChatClient
    setupListeners(); // Add event listeners

    // Set up UI elements for code access
    editMessage = findViewById(R.id.etMessageText);
    }
    Copy
  3. Instantiate the ChatClient

    To implement peer-to-peer messaging, you use Chat SDK to initialize a ChatClient instance. In the MainActivity class, add the following method before onCreate.

    private void setupChatClient() {
    ChatOptions options = new ChatOptions();
    if (appKey.isEmpty()) {
    showLog("You need to set your AppKey");
    return;
    }
    options.setAppKey(appKey); // Set your app key in options
    agoraChatClient = ChatClient.getInstance();
    agoraChatClient.init(this, options); // Initialize the ChatClient
    agoraChatClient.setDebugMode(true); // Enable debug info output
    }
    Copy
  4. Handle and respond to Chat events

    To receive notification of Chat events such as connection, disconnection, and token expiration, you add a ConnectionListener. To handle message delivery and new message notifications, you add a MessageListener. When you receive the onMessageReceived notification, you display the message to the user.

    In /app/java/com.example.<projectname>/MainActivity, add the following method after setupChatClient:

    private void setupListeners() {
    // Add message event callbacks
    agoraChatClient.chatManager().addMessageListener(new MessageListener() {
    @Override
    public void onMessageReceived(List<ChatMessage> messages) {
    for (ChatMessage message : messages) {
    runOnUiThread(() ->
    displayMessage(((TextMessageBody) message.getBody()).getMessage(),
    false)
    );
    showLog("Received a " + message.getType().name()
    + " message from " + message.getFrom());
    }
    }
    });

    // Add connection event callbacks
    agoraChatClient.addConnectionListener(new ConnectionListener() {
    @Override
    public void onConnected() {
    showLog("Connected");
    }

    @Override
    public void onDisconnected(int error) {
    if (isJoined) {
    showLog("Disconnected: " + error);
    isJoined = false;
    }
    }

    @Override
    public void onLogout(int errorCode) {
    showLog("User logging out: " + errorCode);
    }

    @Override
    public void onTokenExpired() {
    // The token has expired
    }

    @Override
    public void onTokenWillExpire() {
    // The token is about to expire. Get a new token
    // from the token server and renew the token.
    }
    });
    }
    Copy
  5. Log in to Chat

    When a user clicks Join, your app logs in to Chat. When a user clicks Leave, the app logs out of Chat.

    To implement this logic, in the MainActivity class, add the following method before onCreate:

    public void joinLeave(View view) {
    Button button = findViewById(R.id.btnJoinLeave);

    if (isJoined) {
    agoraChatClient.logout(true, new CallBack() {
    @Override
    public void onSuccess() {
    showLog("Sign out success!");
    runOnUiThread(() -> button.setText("Join"));
    isJoined = false;
    }
    @Override
    public void onError(int code, String error) {
    showLog(error);
    }
    });
    } else {
    agoraChatClient.loginWithAgoraToken(userId, token, new CallBack() {
    @Override
    public void onSuccess() {
    showLog("Signed in");
    isJoined = true;
    runOnUiThread(() -> button.setText("Leave"));
    }
    @Override
    public void onError(int code, String error) {
    if (code == 200) { // Already joined
    isJoined = true;
    runOnUiThread(() -> button.setText("Leave"));
    } else {
    showLog(error);
    }
    }
    });
    }
    }
    Copy
  6. Send a message

    To send a message to Chat when a user presses the Send button, add the following method to the MainActivity class, before onCreate:

    public void sendMessage(View view) {
    // Read the recipient name from the EditText box
    String toSendName = ((EditText) findViewById(R.id.etRecipient)).getText().toString().trim();
    String content = editMessage.getText().toString().trim();

    if (toSendName.isEmpty() || content.isEmpty()) {
    showLog("Enter a recipient name and a message");
    return;
    }

    // Create a ChatMessage
    ChatMessage message = ChatMessage.createTextSendMessage(content, toSendName);

    // Set the message callback before sending the message
    message.setMessageStatusCallback(new CallBack() {
    @Override
    public void onSuccess() {
    showLog("Message sent");
    runOnUiThread(() -> {
    displayMessage(content, true);
    // Clear the box and hide the keyboard after sending the message
    editMessage.setText("");
    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(editMessage.getApplicationWindowToken(),0);
    });
    }

    @Override
    public void onError(int code, String error) {
    showLog(error);
    }
    });

    // Send the message
    agoraChatClient.chatManager().sendMessage(message);
    }
    Copy
  7. Display chat messages

    To display the messages the current user has sent and received in your app, add the following method to the MainActivity class:

    void displayMessage(String messageText, boolean isSentMessage) {
    // Create a new TextView
    final TextView messageTextView = new TextView(this);
    messageTextView.setText(messageText);
    messageTextView.setPadding(10,10,10,10);

    // Set formatting
    LinearLayout messageList = findViewById(R.id.messageList);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);

    if (isSentMessage) {
    params.gravity = Gravity.END;
    messageTextView.setBackgroundColor(Color.parseColor("#DCF8C6"));
    params.setMargins(100,25,15,5);
    } else {
    messageTextView.setBackgroundColor(Color.parseColor("white"));
    params.setMargins(15,25,100,5);
    }

    // Add the message TextView to the LinearLayout
    messageList.addView(messageTextView, params);
    }
    Copy

Test your implementation

To ensure that you have implemented Peer-to-Peer Messaging in your app:

  1. Create an app instance for the first user:

    1. Register a user in Agora Console and Generate a user token.

    2. In the MainActivity class, update userId, token, and appKey with values from Agora Console. To get your app key, see Get Chat project information.

    3. Connect a physical Android device to your development device.

    4. In Android Studio, click Run app. A moment later you see the project installed on your device.

  2. Create an app instance for the second user:

    1. Register a second user in Agora Console and generate a user token.

    2. In the MainActivity class, update userId and token with values for the second user. Make sure you use the same appKey as for the first user.

    3. Run the modified app on a device emulator or a second physical Android device.

  3. On each device, click Join to log in to Chat.

  4. Edit the recipient name on each device to show the user ID of the user logged in to the other device.

  5. Type a message in the Message box of either device and press >>.

    The message is sent and appears on the other device.

  6. Press Leave to log out of Chat.

Reference

This section contains content that completes the information in this page, or points you to documentation that explains other aspects to this product.

Next steps

In a production environment, best practice is to deploy your own token server. Users retrieve a token from the token server to log in to Chat. To see how to implement a server that generates and serves tokens on request, see Secure authentication with tokens.

vundefined