Exoplayer IMA 拡張機能を使ってみる

IMA SDK を使用すると、マルチメディア広告をウェブサイトやアプリに簡単に統合できます。IMA SDK は、 VAST 準拠のあらゆる広告サーバーから広告をリクエストし、アプリでの広告再生を管理できます。IMA クライアントサイド SDK を使用すると、コンテンツ動画の再生を制御しながら、SDK で広告の再生を処理できます。広告は、アプリのコンテンツ動画プレーヤーの上に配置された別の動画プレーヤーで再生されます。

このガイドでは、ExoPlayer IMA 拡張機能を使用して、IMA SDK を空の Android Studio プロジェクトに統合する方法を説明します。完成したサンプル統合を表示または実行する場合は、GitHub から BasicExample をダウンロードしてください。

IMA クライアントサイドの概要

IMA クライアントサイドの実装には、このガイドで説明する 4 つの主要な SDK コンポーネントが含まれます。

  • AdDisplayContainer: IMA が広告の UI 要素をレンダリングし、アクティブ ビューオープン測定などの視認性を測定する場所を指定するコンテナ オブジェクト。
  • AdsLoader: 広告をリクエストし、広告リクエスト レスポンスからのイベントを処理するオブジェクト。広告ローダは 1 つだけインスタンス化し、アプリのライフサイクル全体で再利用する必要があります。
  • AdsRequest: 広告リクエストを定義するオブジェクト。広告リクエストでは、VAST 広告タグの URL と、広告のサイズなどの追加パラメータを指定します。
  • AdsManager: 広告リクエストに対するレスポンスを含み、広告の再生を制御し、SDK によって発生した広告イベントをリッスンするオブジェクト。

前提条件

始める前に、Android Studio 3.0 以降が必要です。

1. 新しい Android Studio プロジェクトの作成

Android Studio プロジェクトを作成する手順は次のとおりです。

  1. Android Studio を起動します。
  2. [Start a new Android Studio project] を選択します。
  3. [Choose your project] ページで、[Empty Activity] テンプレートを選択します。
  4. [次へ] をクリックします。
  5. [プロジェクトを構成する] ページで、プロジェクトに名前を付け、言語として Java を選択します。
  6. [完了] をクリックします。

2. ExoPlayer IMA 拡張機能をプロジェクトに追加する

まず、アプリケーション レベルの build.gradle ファイルで、依存関係のセクションに拡張機能のインポートを追加します。ExoPlayer IMA 拡張機能のサイズが大きいため、ここで multidex を実装して有効にします。これは、minSdkVersion が 20 以下に設定されているアプリで必要です。また、Java バージョンの互換性情報を指定する新しい compileOptions を追加します。

apply plugin: 'com.android.application'

android {
    namespace 'com.google.ads.interactivemedia.v3.samples.exoplayerexample'
    compileSdk 36

    // Java 17 required by Gradle 8+
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    defaultConfig {
        applicationId "com.google.ads.interactivemedia.v3.samples.exoplayerexample"
        minSdkVersion 21
        targetSdkVersion 36
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    google()
    mavenCentral()
}

dependencies {
    def media3_version = "1.8.0"
    implementation "androidx.media3:media3-ui:$media3_version"
    implementation "androidx.media3:media3-exoplayer:$media3_version"

    // The library adds the IMA ExoPlayer integration for ads.
    implementation "androidx.media3:media3-exoplayer-ima:$media3_version"

    implementation 'androidx.multidex:multidex:2.0.1'
}

3. 広告 UI コンテナを作成する

androidx.media3.ui.PlayerView を作成して、ExoPlayer PlayerView として使用するビューを作成します。また、androidx.constraintlayout.widget.ConstraintLayoutLinearLayout に変更します。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MyActivity"
    tools:ignore="MergeRootFrame">

    <androidx.media3.ui.PlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- UI element for viewing SDK event log -->
    <TextView
        android:id="@+id/logText"
        android:gravity="bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLines="100"
        android:scrollbars="vertical"
        android:textSize="@dimen/font_size">
    </TextView>

</LinearLayout>

4. ExoPlayer IMA 拡張機能をインポートする

ExoPlayer 拡張機能の import ステートメントを追加します。

import static android.os.Build.VERSION.SDK_INT;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.TextView;
import androidx.media3.common.MediaItem;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.ima.ImaAdsLoader;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.ui.PlayerView;
import androidx.multidex.MultiDex;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;

次に、PlayerViewExoPlayerImaAdsLoaderImaSdkSettings の非公開変数を追加して、Activity を拡張するように MainActivity クラスを更新します。

/** Main Activity. */
@SuppressLint("UnsafeOptInUsageError")
/* @SuppressLint is needed for new media3 APIs. */
public class MyActivity extends Activity {

  private static final String SAMPLE_VIDEO_URL =
      "https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
  private static final String SAMPLE_VAST_TAG_URL =
      "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
          + "single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90"
          + "&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&correlator=";
  private static final String LOG_TAG = "ImaExoPlayerExample";

  private PlayerView playerView;
  private TextView logText;
  private ExoPlayer player;
  private ImaAdsLoader adsLoader;
  private ImaSdkSettings imaSdkSettings;

5. adsLoader インスタンスを作成する

onCreate メソッドをオーバーライドし、必要な変数割り当てを追加して、広告タグ URL を含む新しい adsLoader オブジェクトを作成します。

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

  // Initialize the IMA SDK as early as possible when the app starts. If your app already
  // overrides Application.onCreate(), call this method inside the onCreate() method.
  // https://developer.android.com/topic/performance/vitals/launch-time#app-creation
  ImaSdkFactory.getInstance().initialize(this, getImaSdkSettings());

  playerView = findViewById(R.id.player_view);

  // Create an AdsLoader.
  adsLoader =
      new ImaAdsLoader.Builder(/* context= */ this)
          .setAdEventListener(buildAdEventListener())
          .setImaSdkSettings(getImaSdkSettings())
          .build();
}

デバッグ用に IMA イベントをロギングする AdEventListener オブジェクトを返す buildAdEventListener() メソッドを作成します。ExoPlayer IMA 拡張機能はすでに IMA イベントを処理しているため、ここで追加の処理を行う必要はありません。

public AdEvent.AdEventListener buildAdEventListener() {
  logText = findViewById(R.id.logText);
  logText.setMovementMethod(new ScrollingMovementMethod());

  return event -> {
    AdEvent.AdEventType eventType = event.getType();
    if (eventType == AdEvent.AdEventType.AD_PROGRESS) {
      return;
    }
    String log = "IMA event: " + eventType;
    if (logText != null) {
      logText.append(log + "\n");
    }
    Log.i(LOG_TAG, log);
  };
}

ImaSdkSettings オブジェクトを返して IMA SDK の設定を行う getImaSdkSettings() ヘルパー メソッドを作成します。

private ImaSdkSettings getImaSdkSettings() {
  if (imaSdkSettings == null) {
    imaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
    // Set any IMA SDK settings here.
  }
  return imaSdkSettings;
}

6. プレーヤーを初期化してリリースする

プレーヤーをリリースして初期化するメソッドを追加します。initializePlayer() メソッドで ExoPlayer を作成します。次に、AdsMediaSource を作成してプレーヤーに設定します。

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

private void initializePlayer() {
  // Set up the factory for media sources, passing the ads loader and ad view providers.
  DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);

  MediaSource.Factory mediaSourceFactory =
      new DefaultMediaSourceFactory(dataSourceFactory)
          .setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, playerView);

  // Create an ExoPlayer and set it as the player for content and ads.
  player = new ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory).build();
  playerView.setPlayer(player);
  adsLoader.setPlayer(player);

  // Create the MediaItem to play, specifying the content URI and ad tag URI.
  Uri contentUri = Uri.parse(SAMPLE_VIDEO_URL);
  Uri adTagUri = Uri.parse(SAMPLE_VAST_TAG_URL);
  MediaItem mediaItem =
      new MediaItem.Builder()
          .setUri(contentUri)
          .setAdsConfiguration(new MediaItem.AdsConfiguration.Builder(adTagUri).build())
          .build();

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

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

7. プレーヤー イベントを処理する

最後に、プレーヤーのライフサイクル イベントのコールバックを作成します。

  • onStart
  • onResume
  • onStop
  • onPause
  • onDestroy
@Override
public void onStart() {
  super.onStart();
  if (SDK_INT > 23) {
    initializePlayer();
    if (playerView != null) {
      playerView.onResume();
    }
  }
}

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

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

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

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

  super.onDestroy();
}

これで、IMA SDK を使用して広告をリクエストし、表示できるようになりました。より高度な機能については、他のガイドまたは GitHub のサンプルをご覧ください。