バックグラウンドの音声広告の再生

このガイドは、Android アプリにオーディオ広告を読み込むことに関心をお持ちのパブリッシャー様を対象としています。

前提条件

  • IMA Android SDK バージョン 3.16.1 以降。

パブリッシャーにオーディオ プレーヤー アプリがない場合は、出発点として GitHub のオーディオ プレーヤーの例を参照することをおすすめします。この例では、ExoPlayer をフォアグラウンド プレーヤーとして使用しています。これ以降は、IMA 広告のバックグラウンド オーディオ再生に必要な機能について説明します。

バックグラウンド再生をアプリに追加する

アプリがバックグラウンド モードのときに音楽とオーディオ広告の再生を継続するには、カスタム オーディオ プレーヤーと広告ローダーを含む Service コンポーネントを作成します。

アプリに音声再生用の MainActivityAudioPlayerService がある場合は、次のように AndroidManifest.xml ファイルを変更できます。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="…">
  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
  <application … >
    <activity android:name=".MainActivity" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <service android:name=".AudioPlayerService"
             android:exported="false"/>
  </application>
</manifest>

このサービスでは、カスタム オーディオ プレーヤーを作成できます。これは、IMA SDK を操作するための VideoAdPlayer インターフェースを実装している任意のメディア プレーヤーでも使用できます。

IMA SDK v. 3.16.1 では、広告ローダがオーディオ広告をリクエストするための専用のコンテナを作成する新しい機能 createAudioAdDisplayContainer が追加されました。

次のコード スニペットは、オーディオ広告リクエストを初期化して実行する AudioPlayerService の例を示しています。

import android.app.Service;

import com.google.ads.interactivemedia.v3.api.AdDisplayContainer;
import com.google.ads.interactivemedia.v3.api.AdsLoader;
import com.google.ads.interactivemedia.v3.api.AdsRequest;
import com.google.ads.interactivemedia.v3.api.CompanionAdSlot;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer;

import com.google.common.collect.ImmutableList;

/** Plays music and ads even when the app enters background mode. */
public class AudioPlayerService extends Service {

  /**
   * A custom audio player that implements the `VideoAdPlayer` interface.
   */
  private VideoAdPlayer audioPlayer;

  /**
   * An object to create other SDK objects: `AdDisplayContainer`, `AdsLoader` and `AdRequest`.
   */
  private ImaSdkFactory sdkFactory;

  /**
   * An object to make ad requests that would return an `AdsManager`.
   */
  private AdsLoader adsLoader;

  /**
   * An optional list of ViewGroup for rendering companion banners.
   */
  private ImmutableList<CompanionAdSlot> companionAdSlots;

  /**
   * Creates an AdsLoader for requesting ads and handling ad events.
   */
  public void initializeAds() {
    sdkFactory = ImaSdkFactory.getInstance();
    ImaSdkSettings imaSdkSettings = ImaSdkFactory.getInstance().createImaSdkSettings();
    AdDisplayContainer container = ImaSdkFactory.createAudioAdDisplayContainer(this, audioPlayer);
    if (companionAdSlots != null) {
      container.setCompanionSlots(companionAdSlots);
    }
    adsLoader = sdkFactory.createAdsLoader(this, imaSdkSettings, container);

    // Adds event handling logic for ads.
    // For more details, see
    // https://developers.google.com/interactive-media-ads/docs/sdks/android#create-an-adsloader
    adsLoader.addAdsLoadedListener(…);
    adsLoader.addAdErrorListener(…);
  }

  /**
   * Adds a companion ad slot. This slot is not required but can be set in ads initialization.
   *
   * @param companionAdSlot UI container for rendering companion banners.
   */
  public void addCompanionAdSlot(CompanionAdSlot companionAdSlot) {
    this.companionAdSlots = ImmutableList.of(companionAdSlot);
  }

  /**
   * Makes an audio ad request.
   *
   * @param adTagUrl Url to download an ad tag.
   */
  public void requestAd(String adTagUrl) {
    AdsRequest request = sdkFactory.createAdsRequest();
    request.setAdTagUrl(adTagUrl);
    adsLoader.requestAds(request);
  }
  ...
}

広告にコンパニオン広告スロットを使用する

広告は、コンパニオン広告スロットの有無にかかわらず初期化できます。コンパニオン広告を表示する場合は、次に示すように、サービス バインダを介して MainActivity クラスに対する AudioPlayerService へのアクセスを提供する必要があります。

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;
...
/** Plays music and ads even when the app enters background mode. */
public class AudioPlayerService extends Service {
  ...
  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return new ServiceBinder(this);
  }

  /**
   * Provides access to the `AudioPlayerService` instance after binding.
   */
  public class ServiceBinder extends Binder {
    private final AudioPlayerService boundService;

    /**
     * @param service The bound instance of the service
     */
    public ServiceBinder(AudioPlayerService service) {
      boundService = service;
    }

    public AudioPlayerService getBoundService() {
      return boundService;
    }
  }
}

MainActivity クラスの広告を初期化する際に、addCompanionAdSlot() 関数を呼び出してコンパニオン バナー広告を表示するための UI コンテナを渡すことができます。

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.ViewGroup;

import com.google.ads.interactivemedia.v3.api.CompanionAdSlot;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;

public class MainActivity extends Activity {

  private AudioPlayerService boundService;
  private ServiceConnection connection;

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

    ImaSdkFactory sdkFactory = ImaSdkFactory.getInstance();

    ViewGroup companionView = findViewById(R.id.companionAdSlotFrame);
    final CompanionAdSlot companionAdSlot = sdkFactory.createCompanionAdSlot();
    companionAdSlot.setContainer(companionView);
    companionAdSlot.setSize(640, 640);

    connection =
        new ServiceConnection() {
          @Override
          public void onServiceConnected(ComponentName name, IBinder binder) {
            boundService = ((AudioPlayerService.ServiceBinder) binder).getBoundService();
            boundService.addCompanionAdSlot(companionAdSlot);
            boundService.initializeAds();
          }
          ...
        };
    ...
    bindService(intent, connection, Context.BIND_AUTO_CREATE);
  }
  ...
}

問題が発生した場合は、オーディオ プレーヤーの例と実装を比較してください。バックグラウンド オーディオ広告再生に関するその他の質問については、IMA SDK フォーラムをご利用ください。