Suggestions

close search

Back to Text Chat Overview

Text Chat Step 2: Implementing text chat functionality

  1. 1
    Text Chat Step 1:
    Set up text chat
  2. 2
    Text Chat Step 2:
    Implementing text chat
  3. 3
    Text Chat Step 3:
    Text Chat UI improvements

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

git checkout signaling.step-2

This page shows the difference between this branch and the signaling.step-1 branch, which this branch builds from.

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);
    }
}
  1. 1
    Text Chat Step 1:
    Set up text chat
  2. 2
    Text Chat Step 2:
    Implementing text chat
  3. 3
    Text Chat Step 3:
    Text Chat UI improvements