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

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

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

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

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

  • AdDisplayContainer: 広告をレンダリングするコンテナ オブジェクト。
  • 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. [プロジェクトの選択] ページで、[Empty Activity] テンプレートを選択します。
  4. [次へ] をクリックします。
  5. [Configure your project] ページでプロジェクトに名前を付け、言語として Java を選択します。
  6. [Finish] をクリックします。

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

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

app/build.gradle
android {
    namespace 'com.google.ads.interactivemedia.v3.samples.exoplayerexample'
    compileSdkVersion 34

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
  }

  defaultConfig {
      applicationId "com.google.ads.interactivemedia.v3.samples.exoplayerexample"
      minSdkVersion 21
      targetSdkVersion 34
      multiDexEnabled true
      versionCode 1
      versionName "1.0"
  }

    ...
}
dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.media3:media3-ui:1.2.1'
    implementation 'androidx.media3:media3-exoplayer:1.2.1'
    implementation 'androidx.media3:media3-exoplayer-ima:1.2.1'

    ...
}

IMA SDK で広告のリクエストに必要なユーザー権限を追加します。

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.project name">

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

    ...

</manifest>

インテント宣言を追加する

Android 11(API レベル 30)以降をターゲットとするアプリの場合、IMA SDK の最新バージョンおよび最近のバージョンでウェブリンクを開くには、インテントを明示的に宣言する必要があります。広告のクリック([詳細] ボタンをクリックするユーザー)を有効にするには、次のスニペットをアプリのマニフェスト ファイルに追加します。
  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.project name">

      ...

    </application>

    <queries>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="https" />
      </intent>
      <intent>
          <action android:name="android.intent.action.VIEW" />
          <data android:scheme="http" />
      </intent>
    </queries>
  </manifest>

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

適切な ID で StyledPlayerView オブジェクトを作成して、ExoPlayer PlayerView として使用するビューを作成します。また、androidx.constraintlayout.widget.ConstraintLayoutLinearLayout に変更します。

app/src/main/res/layout/activity_main.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">

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

</LinearLayout>

4. 広告リクエスト用のコンテンツ URL と広告タグ URL を追加します

strings.xml にエントリを追加して、コンテンツの URL と VAST 広告タグ URL を保存します。

app/src/main/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?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&impl=s&correlator=]]></string>

</resources>

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

ExoPlayer 拡張機能のインポート ステートメントを追加します。次に、PlayerViewSimpleExoPlayerImaAdsLoader のプライベート変数を追加して、Activity を拡張するように MainActivity クラスを更新します。

app/src/main/java/com/example/project name/MainActivity.java

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import androidx.media3.common.MediaItem;
import androidx.media3.common.util.Util;
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;

...

public class MainActivity extends Activity {

  private PlayerView playerView;
  private ExoPlayer player;
  private ImaAdsLoader adsLoader;

}

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

onCreate メソッドを上書きし、必要な変数割り当てを追加して、広告タグ URL を持つ新しい adsLoader オブジェクトを作成します。

app/src/main/java/com/example/project name/MainActivity.java

...

public class MainActivity extends Activity {

  private PlayerView playerView;
  private ExoPlayer player;
  private ImaAdsLoader adsLoader;

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

    playerView = findViewById(R.id.player_view);

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

  public AdEvent.AdEventListener buildAdEventListener() {

    AdEvent.AdEventListener imaAdEventListener = event -> {
      AdEvent.AdEventType eventType = event.getType();
      // Log IMA events for debugging.
      // The ExoPlayer IMA extension already handles IMA events and does not need anything
      // additional here to function.
    };

    return imaAdEventListener;
  }

}

7. プレーヤーを初期化して解放する

プレーヤーを初期化して解放するメソッドを追加します。初期化メソッドで、SimpleExoPlayer を作成します。次に、AdsMediaSource を作成してプレーヤーに設定します。

app/src/main/java/com/example/project name/MainActivity.java
public class MainActivity extends Activity {

  ...

  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(getString(R.string.content_url));
    Uri adTagUri = Uri.parse(getString(R.string.ad_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);
  }
}

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

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

  • onStart
  • onResume
  • onStop
  • onPause
  • onDestroy
app/src/main/java/com/example/project name/MainActivity.java
public class MainActivity extends Activity {

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

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

      playerView = findViewById(R.id.player_view);

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

  @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();
  }

  ...

}

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