Suggestions

close search

Back to Tutorials

Text Chat Tutorial (Android)

Overview

The OpenTok signaling API lets clients send text messages and other data to other clients connected to the OpenTok session. You can send a signal message to a specific client, or you can send a message to every client connected to the session.

In this tutorial, we will use git to check out a new branch for each step — each branch will provide incremental changes on the last, and we will walk through code for each change. You will not need to add any code to the project during this tutorial.

Step 1: Getting started

The code for this section is in the signaling.step-1 branch of the learning-opentok-android repo, so if you haven't already, you'll need to clone the repo into a local directory and check out the branch — this can be done using the command line:

git clone https://github.com/opentok/learning-opentok-android.git

Then check out the branch:

git checkout signaling.step-1

Open the project in Android Studio to follow along.

Exploring the code

In this branch, the following code is added to the initializeSession() method in the ChatActivity.java file:

mSession.setSignalListener(this);

This sets the ChatActivity object as the implementor of the SubscriberKit.SignalListener interface. This interface defines the onSignalReceived(session, type, data, connection) methods. This method is called when the client receives a signal from the session:

@Override
public void onSignalReceived(Session session, String type, String data, Connection connection) {
    Toast toast = Toast.makeText(this, data, Toast.LENGTH_LONG);
    toast.show();
}

This app uses an android.widget.Toast object to display received signals.

In the onConnected(session) method, the following code sends a signal when the app connects to the session:

mSession.sendSignal("", "Hello, Signaling!");

This signal is sent to all clients connected to the session. The method has two parameters:

Step 2: Implementing text chat functionality

The code for this section is added in the signaling.step-2 branch of the learning-opentok-android repo:

git checkout signaling.step-2

Exploring the code

In this branch, the following code is added to the initializeSession() method:

mSendButton = (Button)findViewById(R.id.send_button);
mMessageEditText = (EditText)findViewById(R.id.message_edit_text);

// Attach handlers to UI
mSendButton.setOnClickListener(this);

The main layout XML file adds a Button and and EditText element to the main view. This code adds properties to reference these objects. It also sets the ChatActivity object as the implementor of the View.OnClickListener interface. This interface defines the onClick(View v) method.

In the onConnected(Session session) method (called when the app connects to the OpenTok session) the following line of code is added in this branch:

enableMessageViews();

The enableMessageViews() method enables the Message text field and the Send button:

private void enableMessageViews() {
    mMessageEditText.setEnabled(true);
    mSendButton.setEnabled(true);
}

The onClick(View v) method is called when the clicks the Send button:

@Override
public void onClick(View v) {
    if (v.equals(mSendButton)) {
        sendMessage();
    }
}

The sendMessage() method sends the text chat message (defined in the Message text field) to the OpenTok session:

private void sendMessage() {
    disableMessageViews();
    mSession.sendSignal(SIGNAL_TYPE_MESSAGE, mMessageEditText.getText().toString());
    mMessageEditText.setText("");
    enableMessageViews();
}

Note that in this branch, the type of the signal is set to SIGNAL_TYPE_MESSAGE (a string defined as "message"). The onSignalReceived() method checks to see if the signal received is of this type:

@Override
public void onSignalReceived(Session session, String type, String data, Connection connection) {
    if (type.equals(SIGNAL_TYPE_CHAT) {
        showMessage(data);
    }
}

Step 3: Text Chat UI improvements

The code for this section is added in the signaling.step-3 branch of the learning-opentok-android repo:

git checkout signaling.step-3

First, let's test the code in this branch:

  1. Find the test.html file in the root of the project. You will use the test.html file to connect to the OpenTok session and view the audio-video stream published by the Android app:

    • Edit the test.html file and set the sessionCredentialsUrl variable to match the ksessionCredentialsUrl property used in the Android app.

    • Add the test.html file to a web server. (You cannot run WebRTC videos in web pages loaded from the desktop.)

    • In a browser, load the test.html file from the web server.

  2. Run the Android app. Enter some chat message in the Message text field, then click the Send button. The web page displays the text message sent by the Android app. You can also send a message from the web page to the Android app.

Instead of using a Toast object to display received signals, the code in this branch uses an android.widget.ListView object. This lets the app display more than one message at a time. This branch adds the following code to the onCreate() method:

mMessageHistoryListView = (ListView)findViewById(R.id.message_history_list_view);

// Attach data source to message history
mMessageHistory = new ChatMessageAdapter(this);
mMessageHistoryListView.setAdapter(mMessageHistory);

This branch adds code that differentiates between signals (text chat messages) sent from the local Android client and those sent from other clients connected to the session. The onSignalReceived(session, type, data, connection) method checks the Connection object for the received signal with the Connection object returned by mSession.getConnection():

@Override
public void onSignalReceived(Session session, String type, String data, Connection connection) {
    if (connection != null)
        boolean remote = !connection.equals(mSession.getConnection());
        if (type.equals(SIGNAL_TYPE_CHAT) {
            showMessage(data, remote);
        }
    }
}

The Connection object of the received signal represents the connection to the session for the client that sent the signal. This will only match the Connection object returned by mSession.getConnection() if the signal was sent by the local client.

The showMessage(messageData, remote) method has a new second parameter: remote. This is set to true if the message was sent another client (and false if it was sent by the local Android client):

private void showMessage(String messageData, boolean remote) {
    ChatMessage message = ChatMessage.fromData(messageData);
    message.setRemote(remote);
    mMessageHistory.add(message);
 }

The ChatMessage.fromData() method converts the message data (the data in the received signal) into a ChatMessage object. The mMessageHistoryListView uses the mMessageHistory object as the adaptor for the data in the list view. The mMessageHistory property is an android.widget.ArrayAdapter object. This tutorial focuses on the OpenTok Android SDK API. For more information on the Android classes used in this text chat implementation, see the docs for the ArrayAdaptor and ListView

Congratulations! You've finished Text Chat Tutorial for Android.
You can continue to play with and adjust the code you've developed here, or check out the Next Steps below. For more information on signaling, see the OpenTok signaling developer guide.