背景音訊廣告播放

本指南適用於有意在 Android 應用程式中載入音訊廣告的發布商。

必要條件

  • IMA Android SDK 3.16.1 以上版本。

如果發布商目前沒有音訊播放器應用程式,建議發布商參考 GitHub 上的音訊播放器範例。這個範例使用 ExoPlayer 做為前景播放器。本指南的其餘部分將說明在背景播放 IMA 廣告所需的功能。

在應用程式中加入背景廣告播放功能

如要在應用程式處於背景模式時繼續播放音樂和音訊廣告,您可以建立包含自訂音訊播放器和廣告載入器的 Service 元件

如果應用程式有 MainActivity 和用於音訊播放的 AudioPlayerService,您可以修改 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>

您可以在服務中建立自訂音訊播放器,只要是實作 VideoAdPlayer 介面以與 IMA SDK 互動的任何媒體播放器,都可以用於此服務。

IMA SDK 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 論壇尋求支援。