תמיכה במודעות אודיו ברקע

המדריך הזה מיועד לבעלי אפליקציות שרוצים לטעון מודעות אודיו באפליקציות שלהם ל-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.

בגרסה 3.16.1 של IMA SDK נוספה פונקציה חדשה, 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);
  }
  ...
}

שימוש במודעות עם מיקומי מודעות נלוות

אפשר להפעיל מודעות עם או בלי מיקומי מודעות נלוות. אם אתם בוחרים להציג מודעות נלוות, אתם צריכים לספק גישה של AudioPlayerService למחלקה MainActivity דרך קובץ binder של שירות, כמו שמוצג בהמשך:

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;
    }
  }
}

אפשר להפעיל את הפונקציה addCompanionAdSlot() ולהעביר מאגר של ממשק משתמש כדי לעבד מודעות באנר נלוות כשמפעילים מודעות מהמחלקה MainActivity.

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);
  }
  ...
}

אם נתקלתם בבעיה, אתם יכולים להשוות את ההטמעה שלכם לדוגמה של נגן אודיו. אם יש לכם שאלות נוספות לגבי הפעלה של מודעות אודיו ברקע, אתם יכולים לפנות לתמיכה דרך מרכז העזרה של Ad Manager.