Skip to main content

You are viewing Agora Docs forBeta products and features. Switch to Docs

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:


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

      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>:


    _4
    <uses-permission android:name="android.permission.INTERNET" />
    _4
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    _4
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    _4
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />

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:


_65
<?xml version="1.0" encoding="utf-8"?>
_65
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
_65
android:layout_width="match_parent"
_65
android:layout_height="match_parent"
_65
android:background="#ECE5DD">
_65
_65
<Button
_65
android:id="@+id/btnJoinLeave"
_65
android:layout_width="wrap_content"
_65
android:layout_height="wrap_content"
_65
android:layout_alignParentEnd="true"
_65
android:layout_alignParentTop="true"
_65
android:layout_margin="5dp"
_65
android:onClick="joinLeave"
_65
android:text="Join" />
_65
_65
<EditText
_65
android:id="@+id/etRecipient"
_65
android:layout_width="match_parent"
_65
android:layout_height="wrap_content"
_65
android:layout_alignBottom="@id/btnJoinLeave"
_65
android:layout_alignTop="@id/btnJoinLeave"
_65
android:layout_toStartOf="@id/btnJoinLeave"
_65
android:layout_margin="5dp"
_65
android:padding="5dp"
_65
android:background="#FFFFFF"
_65
android:hint="Enter recipient user ID" />
_65
_65
<ScrollView
_65
android:id="@+id/scrollView"
_65
android:layout_width="match_parent"
_65
android:layout_height="match_parent"
_65
android:layout_above="@id/btnSendMessage"
_65
android:layout_below="@id/etRecipient"
_65
android:background="#ECE5DD">
_65
_65
<LinearLayout
_65
android:id="@+id/messageList"
_65
android:layout_width="match_parent"
_65
android:layout_height="wrap_content"
_65
android:orientation="vertical">
_65
</LinearLayout>
_65
</ScrollView>
_65
_65
<EditText
_65
android:id="@+id/etMessageText"
_65
android:layout_width="match_parent"
_65
android:layout_height="wrap_content"
_65
android:layout_toStartOf="@id/btnSendMessage"
_65
android:layout_alignBottom="@id/btnSendMessage"
_65
android:layout_margin="5dp"
_65
android:padding="5dp"
_65
android:background="#FFFFFF"
_65
android:hint="Message" />
_65
_65
<Button
_65
android:id="@+id/btnSendMessage"
_65
android:layout_width="50dp"
_65
android:layout_margin="5dp"
_65
android:layout_height="wrap_content"
_65
android:layout_alignParentEnd="true"
_65
android:layout_alignParentBottom="true"
_65
android:onClick="sendMessage"
_65
android:text=">>" />
_65
</RelativeLayout>

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>:


    _19
    import android.widget.Button;
    _19
    import android.widget.EditText;
    _19
    import android.widget.LinearLayout;
    _19
    import android.widget.TextView;
    _19
    import android.view.View;
    _19
    import android.widget.Toast;
    _19
    import android.graphics.Color;
    _19
    import android.view.Gravity;
    _19
    import android.view.inputmethod.InputMethodManager;
    _19
    import android.util.Log;
    _19
    import java.util.List;
    _19
    _19
    import io.agora.CallBack;
    _19
    import io.agora.ConnectionListener;
    _19
    import io.agora.MessageListener;
    _19
    import io.agora.chat.ChatClient;
    _19
    import io.agora.chat.ChatMessage;
    _19
    import io.agora.chat.ChatOptions;
    _19
    import io.agora.chat.TextMessageBody;

  2. Log events and show status updates to your users

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


    _8
    private void showLog(String text) {
    _8
    // Show a toast message
    _8
    runOnUiThread(() ->
    _8
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show());
    _8
    _8
    // Write log
    _8
    Log.d("AgoraChatQuickStart", text);
    _8
    }

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:


    _7
    private String userId = "<User ID of the local user>";
    _7
    private String token = "<Your authentication token>";
    _7
    private String appKey = "<App key from Agora console>";
    _7
    _7
    private ChatClient agoraChatClient;
    _7
    private boolean isJoined = false;
    _7
    EditText editMessage;

  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:


    _11
    @Override
    _11
    protected void onCreate(Bundle savedInstanceState) {
    _11
    super.onCreate(savedInstanceState);
    _11
    setContentView(R.layout.activity_main);
    _11
    _11
    setupChatClient(); // Initialize the ChatClient
    _11
    setupListeners(); // Add event listeners
    _11
    _11
    // Set up UI elements for code access
    _11
    editMessage = findViewById(R.id.etMessageText);
    _11
    }

  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.


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

  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:


    _48
    private void setupListeners() {
    _48
    // Add message event callbacks
    _48
    agoraChatClient.chatManager().addMessageListener(new MessageListener() {
    _48
    @Override
    _48
    public void onMessageReceived(List<ChatMessage> messages) {
    _48
    for (ChatMessage message : messages) {
    _48
    runOnUiThread(() ->
    _48
    displayMessage(((TextMessageBody) message.getBody()).getMessage(),
    _48
    false)
    _48
    );
    _48
    showLog("Received a " + message.getType().name()
    _48
    + " message from " + message.getFrom());
    _48
    }
    _48
    }
    _48
    });
    _48
    _48
    // Add connection event callbacks
    _48
    agoraChatClient.addConnectionListener(new ConnectionListener() {
    _48
    @Override
    _48
    public void onConnected() {
    _48
    showLog("Connected");
    _48
    }
    _48
    _48
    @Override
    _48
    public void onDisconnected(int error) {
    _48
    if (isJoined) {
    _48
    showLog("Disconnected: " + error);
    _48
    isJoined = false;
    _48
    }
    _48
    }
    _48
    _48
    @Override
    _48
    public void onLogout(int errorCode) {
    _48
    showLog("User logging out: " + errorCode);
    _48
    }
    _48
    _48
    @Override
    _48
    public void onTokenExpired() {
    _48
    // The token has expired
    _48
    }
    _48
    _48
    @Override
    _48
    public void onTokenWillExpire() {
    _48
    // The token is about to expire. Get a new token
    _48
    // from the token server and renew the token.
    _48
    }
    _48
    });
    _48
    }

  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:


    _36
    public void joinLeave(View view) {
    _36
    Button button = findViewById(R.id.btnJoinLeave);
    _36
    _36
    if (isJoined) {
    _36
    agoraChatClient.logout(true, new CallBack() {
    _36
    @Override
    _36
    public void onSuccess() {
    _36
    showLog("Sign out success!");
    _36
    runOnUiThread(() -> button.setText("Join"));
    _36
    isJoined = false;
    _36
    }
    _36
    @Override
    _36
    public void onError(int code, String error) {
    _36
    showLog(error);
    _36
    }
    _36
    });
    _36
    } else {
    _36
    agoraChatClient.loginWithAgoraToken(userId, token, new CallBack() {
    _36
    @Override
    _36
    public void onSuccess() {
    _36
    showLog("Signed in");
    _36
    isJoined = true;
    _36
    runOnUiThread(() -> button.setText("Leave"));
    _36
    }
    _36
    @Override
    _36
    public void onError(int code, String error) {
    _36
    if (code == 200) { // Already joined
    _36
    isJoined = true;
    _36
    runOnUiThread(() -> button.setText("Leave"));
    _36
    } else {
    _36
    showLog(error);
    _36
    }
    _36
    }
    _36
    });
    _36
    }
    _36
    }

  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:


    _36
    public void sendMessage(View view) {
    _36
    // Read the recipient name from the EditText box
    _36
    String toSendName = ((EditText) findViewById(R.id.etRecipient)).getText().toString().trim();
    _36
    String content = editMessage.getText().toString().trim();
    _36
    _36
    if (toSendName.isEmpty() || content.isEmpty()) {
    _36
    showLog("Enter a recipient name and a message");
    _36
    return;
    _36
    }
    _36
    _36
    // Create a ChatMessage
    _36
    ChatMessage message = ChatMessage.createTextSendMessage(content, toSendName);
    _36
    _36
    // Set the message callback before sending the message
    _36
    message.setMessageStatusCallback(new CallBack() {
    _36
    @Override
    _36
    public void onSuccess() {
    _36
    showLog("Message sent");
    _36
    runOnUiThread(() -> {
    _36
    displayMessage(content, true);
    _36
    // Clear the box and hide the keyboard after sending the message
    _36
    editMessage.setText("");
    _36
    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    _36
    inputMethodManager.hideSoftInputFromWindow(editMessage.getApplicationWindowToken(),0);
    _36
    });
    _36
    }
    _36
    _36
    @Override
    _36
    public void onError(int code, String error) {
    _36
    showLog(error);
    _36
    }
    _36
    });
    _36
    _36
    // Send the message
    _36
    agoraChatClient.chatManager().sendMessage(message);
    _36
    }

  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:


    _23
    void displayMessage(String messageText, boolean isSentMessage) {
    _23
    // Create a new TextView
    _23
    final TextView messageTextView = new TextView(this);
    _23
    messageTextView.setText(messageText);
    _23
    messageTextView.setPadding(10,10,10,10);
    _23
    _23
    // Set formatting
    _23
    LinearLayout messageList = findViewById(R.id.messageList);
    _23
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    _23
    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
    _23
    _23
    if (isSentMessage) {
    _23
    params.gravity = Gravity.END;
    _23
    messageTextView.setBackgroundColor(Color.parseColor("#DCF8C6"));
    _23
    params.setMargins(100,25,15,5);
    _23
    } else {
    _23
    messageTextView.setBackgroundColor(Color.parseColor("white"));
    _23
    params.setMargins(15,25,100,5);
    _23
    }
    _23
    _23
    // Add the message TextView to the LinearLayout
    _23
    messageList.addView(messageTextView, params);
    _23
    }

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