Suggestions

close search

Hello World

This hello world procedure will get you the simplest possible Android audio/video chat in 10 minutes. We'll use Android Studio.

Tip: Use Genymotion and a Nexus 10 device to ensure the correct image rotation. Various issues can cause an incorrect rotation of images on Android devices. OpenTok fully supports and works with a wide range of devices at the correct orientation and provides sample code to achieve this. We've left these details out of the following procedure to keep it simple.

Prerequisites

Creating a new Android Studio project

  1. Open Android Studio and select New Project from the File menu.
  2. Set the minimum SDK for the app to be API 16 (Android 4.1, Jelly Bean).
  3. Click through the wizard, ensuring that Empty Activity is selected.

Installing the OpenTok Android SDK

The OpenTok Android SDK is hosted on Maven. To use the SDK in your app, download it from http://tokbox.bintray.com/maven.

  1. Edit the build.gradle for your project and add the following code snippet to the allprojects/repositiories section:

    maven { url  "http://tokbox.bintray.com/maven" }

    The build.gradle file should look like this:

    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:2.1.0'
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
    
    allprojects {
        repositories {
            jcenter()
            maven {
                url  "http://tokbox.bintray.com/maven"
            }
        }
    }
    
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
    
  2. Modify build.gradle for your module (the app/build.gradle file) and add the following code snippet to the dependencies section:
    compile 'com.opentok.android:opentok-android-sdk:2.8.+'
  3. Change the compileSdkVersion number to 22. Change the targetSdkVersion number to 22. And change the appcompat setting to 'com.android.support:appcompat-v7:22.2.0'.

    The OpenTok Android SDK uses the CAMERA permission, which Google classifies as dangerous. Let's set our target SDK to pre-Marshmallow so that we don't have to request permissions at runtime just yet.

    The build.gradle file for your module should look like this:

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 22
        buildToolsVersion "21.1.2"
    
        defaultConfig {
            applicationId "com.example.jeff.myapplication"
            minSdkVersion 16
            targetSdkVersion 22
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:22.2.0'
        compile 'com.opentok.android:opentok-android-sdk:2.8.1+'
    }
          
  4. Sync your project.

Importing the necessary classes

  1. Open the MainActivity.java file. We will work in this file for the remainder of the procedure.
  2. Add the following import statements.
    import android.widget.LinearLayout;
    import android.util.Log;
    import com.opentok.android.Publisher;
    import com.opentok.android.PublisherKit;
    import com.opentok.android.Session;
    import com.opentok.android.Stream;
    import com.opentok.android.Subscriber;
    import com.opentok.android.SubscriberKit;
    import com.opentok.android.OpentokError;

Implementing the OpenTok interfaces

Add the necessary OpenTok interfaces to the class declaration.

public class MainActivity extends AppCompatActivity implements Session.SessionListener,
        Publisher.PublisherListener, Subscriber.SubscriberListener,
        Subscriber.VideoListener {
    ...

Getting an API key, session ID, and token

  1. Sign up for a TokBox Account.
    Free for thirty days. No credit card required.
  2. Use your credentials to log in to your TokBox Account.
  3. Create a project by clicking add project, typing a name, and clicking view project.
  4. Copy the API Key value and paste it into a text file.
  5. Within the Project Tools section, click Create Session ID.
  6. Copy the session ID from the box below the Create Session ID button and paste it into a text file.
  7. Within the Generate Token area, click Generate token.
    Make sure that Publisher is selected in the Role list box.
  8. Copy the token value from the box below the Generate token button and paste it into a text file.

Declaring static and member variables

  1. Returning to the MainActivity.java file, add four static variables to store the API key, session ID, token, and a logging message identifier.
    public static final String API_KEY = "YOUR-API-KEY";
    public static final String SESSION_ID = "YOUR-SESSION-ID";
    public static final String TOKEN = "YOUR-TOKEN";
    public static final String LOGTAG = "MainActivity.class.getName()";
  2. Replace YOUR-API-KEY, YOUR-SESSION-ID, and YOUR-TOKEN with the values from your TokBox Account (see the previous section).

    Important: You can continue to get the session ID and token values from the Project Page of your TokBox Account during testing and development. But before you go into production, you must deploy one of our server SDKs to generate these values dynamically.

  3. We also need some member variables to store references to objects so that we can use them across the class.
    private LinearLayout publisherView;
    private LinearLayout.LayoutParams publisherParams;
    private LinearLayout subscriberView;
    private LinearLayout.LayoutParams subscriberParams;

Joining a session

To join a session, you will need to:

We can just go ahead and use the onCreate() method to do this. While we're in onCreate(), we will also delete the parts of the default onCreate() method that use XML for the views and replace it with some Java that defines a simple LinearLayout. See the full onCreate() method below.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(LOGTAG, "call to onCreate");
    super.onCreate(savedInstanceState);

    LinearLayout parentLayout = new LinearLayout(this);
    setContentView(parentLayout);

    subscriberView = new LinearLayout(this);
    subscriberParams = new LinearLayout.LayoutParams
        (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    subscriberParams.weight = 0.5f;
    subscriberView.setLayoutParams(subscriberParams);

    publisherView = new LinearLayout(this);
    publisherParams = new LinearLayout.LayoutParams
        (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    publisherParams.weight = 0.5f;
    publisherView.setLayoutParams(publisherParams);

    parentLayout.setWeightSum(1f);
    parentLayout.addView(publisherView);
    parentLayout.addView(subscriberView);

    Session session = new Session(MainActivity.this, API_KEY, SESSION_ID);
    session.setSessionListener(this);
    session.connect(TOKEN);
}

Publishing a stream

Once you have joined a session, you can begin to publish the audio and video from the device to the session. This audio/video data is called a stream. To accomplish this:

We'll go ahead and do all of this in an override of the onConnected() method of the SessionListener interface.

@Override
public void onConnected(Session session) {
    Log.i(LOGTAG, "call to onConnected of the SessionListener");
    Publisher publisher = new Publisher(MainActivity.this);
    publisher.setPublisherListener(this);
    publisherView.addView(publisher.getView(), publisherParams);
    session.publish(publisher);
}

Subscribing to a stream

Now one party can see their own video on the device. Next, we add the video of another party so that communication can commence. To accomplish this, we need to:

We can do all of this in a single override of the onStreamReceived() method of the SessionListener interface.

@Override
public void onStreamReceived(Session session, Stream stream) {
    Log.i(LOGTAG, "call to onStreamReceived");
    Subscriber subscriber = new Subscriber(MainActivity.this, stream);
    subscriber.setVideoListener(this);
    session.subscribe(subscriber);
    subscriberView.addView(subscriber.getView(), subscriberParams);
}

Stubbing out the remainder of the required methods

To complete this procedure and just get a very basic audio/video chat going quickly, we will stub out the remainder of the required methods.

@Override
public void onDisconnected(Session session) {
    Log.i(LOGTAG, "call to onDisconnected of the SessionListener");
}

@Override
public void onStreamDropped(Session session, Stream stream) {
    Log.i(LOGTAG, "call to onStreamDropped of the SessionListener");
}

@Override
public void onError(Session session, OpentokError error) {
    Log.i(LOGTAG, "SessionListener error: " + error.getMessage());
}

@Override
public void onStreamCreated(PublisherKit publisher, Stream stream) {
    Log.i(LOGTAG, "call to onStreamCreated of the PublisherListener");
}

@Override
public void onStreamDestroyed(PublisherKit publisher, Stream stream) {
    Log.i(LOGTAG, "call to onStreamDestroyed of the PublisherListener");
}

@Override
public void onError(PublisherKit publisher, OpentokError error) {
    Log.i(LOGTAG, "PublisherListener error: " + error.getMessage());
}

@Override
public void onConnected(SubscriberKit subscriber) {
    Log.i(LOGTAG, "call to onConnected of the SubscriberListener");
}

@Override
public void onDisconnected(SubscriberKit subscriber) {
    Log.i(LOGTAG, "call to onDisconnected of the SubscriberListener");
}

@Override
public void onError(SubscriberKit subscriber, OpentokError error) {
    Log.i(LOGTAG, "SubscriberListener error: " + error.getMessage());
}

@Override
public void onVideoDataReceived(SubscriberKit subscriber) {
    Log.i(LOGTAG, "call to onVideoDataReceived of the VideoListener");
}

@Override
public void onVideoDisabled(SubscriberKit subscriber, java.lang.String reason) {
    Log.i(LOGTAG, "call to onVideoDisabled of the VideoListener");
}

@Override
public void onVideoEnabled(SubscriberKit subscriber, java.lang.String reason) {
    Log.i(LOGTAG, "call to onVideoEnabled of the VideoListener");
}

@Override
public void onVideoDisableWarning(SubscriberKit subscriber) {
    Log.i(LOGTAG, "call to onVideoDisableWarning of the VideoListener");
}

@Override
public void onVideoDisableWarningLifted(SubscriberKit subscriber) {
    Log.i(LOGTAG, "call to onVideoDisableWarning of the VideoListener");
}

Building and running your app

All done! Now, just click the button to build and run the app in your emulator. (Make sure that you have enabled the camera in the emulator.)

How do I add a subscriber?

To get someone else to join the session, try running the app on a supported Android device. Alternatively, you can create a new project following the steps above. Just make sure to use the same API key and session ID. Alternatively, you can use the iOS or JavaScript hello world sample app to create a different client.

What's happening in this code?

What next?

Keep building

You can keep building on this Java code. Visit OpenTok Basics, Developer Guides, and Tutorials to find out how to add more functionality.

Get session IDs and tokens dynamically

Deploy one of our server SDKs to generate unique session IDs and per-user tokens on demand (required for a production app). Download a sample app in the language of your choice for a big head start.

Didn't find your favorite language? You can also access our REST API directly.