Get Started

IMA SDKs make it easy to integrate multimedia ads into your websites and apps. IMA SDKs can request ads from any VAST-compliant ad server and manage ad playback in your apps. With IMA client-side SDKs, you maintain control of content video playback, while the SDK handles ad playback. Ads play in a separate video player positioned on top of the app's content video player.

This guide demonstrates how to integrate the IMA SDK into an empty Android Studio project using the ExoPlayer IMA extension. If you would like to view or follow along with a completed sample integration, download the BasicExample from GitHub.

IMA client-side overview

Implementing IMA client-side involves four main SDK components, which are demonstrated in this guide:

  • AdDisplayContainer: A container object where ads are rendered.
  • AdsLoader: An object that requests ads and handles events from ads request responses. You should only instantiate one ads loader, which can be reused throughout the life of the application.
  • AdsRequest: An object that defines an ads request. Ads requests specify the URL for the VAST ad tag, as well as additional parameters, such as ad dimensions.
  • AdsManager: An object that contains the response to the ads request, controls ad playback, and listens for ad events fired by the SDK.

Prerequisites

Before you begin, you'll need the following:

Setting up your Android Studio project

To create your Android Studio project, follow these steps:

  1. Start Android Studio and select Start a new Android Studio project, or if Android Studio is already running, select File > New > New Project.
  2. Select Empty Activity for the project template.
  3. Name your project and select Java for the language. The IMA SDK is compatible with Kotlin, but this guide is designed for a project made in Java.
  4. Click Finish to create your project.

Adding ExoPlayer and the IMA plugin to your app/build.gradle file

Add the following imports to the dependencies section and a new compileOptions section to the application-level build.gradle file, located at app/build.gradle:

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    ...
}
dependencies {
    implementation 'com.google.android.exoplayer:exoplayer-core:2.11.1'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.1'
    implementation 'com.google.android.exoplayer:extension-ima:2.11.1'

    ...
}

Adding the required user permissions to your AndroidManifest.xml file

Add the following user permissions to the AndroidManifest.xml file. These permissions are required by thr IMA SDK to request ads.

app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.exotest">

    <!-- Required permissions for the IMA SDK -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    ...

</manifest>

Checkpoint

Your app should compile and run, but you haven't yet added UI elements or code to request and display ads. When you initialize and manipulate UI objects, you must do so on the main thread if you're using multiple threads. In Android, UI objects are not thread-safe. See Threads for more information.

Set up the ad UI container

Create the view to be used as the ExopPlayer's PlayerView by creating a RelativeLayout with an appropriate ID in fragment_video.xml. Also change the androidx.constraintlayout.widget.ConstraintLayout to a LinearLayout.

fragment_video.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Ad your content URL and ad tag url

Add entries into strings.xml to store your content URL and VAST ad tag URL.

res/values/strings.xml

<resources>
    <string name="app_name">Your_Project_Name</string>
    <string name="content_url"><![CDATA[https://storage.googleapis.com/gvabox/media/samples/stock.mp4]]></string>
    <string name="ad_tag_url"><![CDATA[https://pubads.g.doubleclick.net/gampad/ads?sz=640x480
    &iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp
    &output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dlinear
    &correlator=]]></string>

</resources>

Integrate ExoPlayer and IMA SDK into MyActivity.java

Add imports and member variables

To use ExoPlayer and the IMA SDK, include the following import statements:

MyActivity.java

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ext.ima.ImaAdsLoader;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.source.ads.AdsMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;

Next, change the MainActivity class to extend Activity and add the following private variables into the class:

MyActivity.java

public class MainActivity extends Activity {

  private PlayerView playerView;
  private SimpleExoPlayer player;
  private ImaAdsLoader adsLoader;

}

Assign the variables when the view is created

Overwrite the onCreate menthod and add the following variable assignments:

MyActivity.java

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

  playerView = findViewById(R.id.player_view);

  // Create an AdsLoader with the ad tag url.
  adsLoader = new ImaAdsLoader(this, Uri.parse(getString(R.string.ad_tag_url)));
}

Create methods to initialize and release the player

Add the following methods to be called to initialize and release the player. In the initialize method, create the simpleExoPlayer. Then, create the AdsMediaSource and set it to the player.

MyActivity.java

private void releasePlayer() {
  adsLoader.setPlayer(null);
  playerView.setPlayer(null);
  player.release();
  player = null;
}

private void initializePlayer() {
  // Create a SimpleExoPlayer and set is as the player for content and ads.
  player = new SimpleExoPlayer.Builder(this).build();
  playerView.setPlayer(player);
  adsLoader.setPlayer(player);

  DataSource.Factory dataSourceFactory =
          new DefaultDataSourceFactory(this, Util.getUserAgent(this, getString(R.string.app_name)));

  ProgressiveMediaSource.Factory mediaSourceFactory =
          new ProgressiveMediaSource.Factory(dataSourceFactory);

  // Create the MediaSource for the content you wish to play.
  MediaSource mediaSource =
          mediaSourceFactory.createMediaSource(Uri.parse(getString(R.string.content_url)));

  // Create the AdsMediaSource using the AdsLoader and the MediaSource.
  AdsMediaSource adsMediaSource =
          new AdsMediaSource(mediaSource, dataSourceFactory, adsLoader, playerView);

  // Prepare the content and ad to be played with the SimpleExoPlayer.
  player.prepare(adsMediaSource);

  // Set PlayWhenReady. If true, content and ads will autoplay.
  player.setPlayWhenReady(false);
}

Create player lifecycle event callbacks

To complete your project, set up the following callbacks for the player's lifecycle events: onStart, onResume, onStop, onPause, and onDestroy. The following code is set up to use onStart/onStop for Android SDK versions 24 and later, and to use onResume/onPause for versions prior to 24:

MyActivity.java

@Override
public void onStart() {
  super.onStart();
  //
  if (Util.SDK_INT > 23) {
    initializePlayer();
    if (playerView != null) {
      playerView.onResume();
    }
  }
}

@Override
public void onResume() {
  super.onResume();
  if (Util.SDK_INT <= 23 || player == null) {
    initializePlayer();
    if (playerView != null) {
      playerView.onResume();
    }
  }
}

@Override
public void onPause() {
  super.onPause();
  if (Util.SDK_INT <= 23) {
    if (playerView != null) {
      playerView.onPause();
    }
    releasePlayer();
  }
}

@Override
public void onStop() {
  super.onStop();
  if (Util.SDK_INT > 23) {
    if (playerView != null) {
      playerView.onPause();
    }
    releasePlayer();
  }
}

@Override
protected void onDestroy() {
  super.onDestroy();
  adsLoader.release();
}

Congrats! You're now requesting and displaying video ads in your Android app. To fine tune your implementation, see Ad Rules and the API documentation.

Troubleshooting

If you're experiencing issues playing a video ad, try downloading the completed BasicExample below and change the ad_tag_url defined in strings.xml to the ad tag URL you're testing with. If it works properly in the BasicExample then there's likely an issue with your app's IMA integration code. Review this guide and API docs to detect any discrepancies.

If you would like to see a more advanced example project, demostrating how to integrate other video players beside ExoPlayer with the IMA SDK, see the Advanced Example on GitHub.

Download BasicExample.zip View on GitHub

Still having issues? Drop us a line in the IMA SDK forum.