This guide is intended for publishers who are interested in loading audio ads to
their Android apps.

> [!IMPORTANT]
> **Important:** We do not recommend playing video ads in background mode.

## Prerequisites

- IMA Android SDK v. 3.16.1 or higher.

We recommend publishers look at the
[Audio Player Example](https://github.com/googleads/googleads-ima-android/tree/main/audioplayerexample)
on github as a starting point if they do not currently have an audio player app.
This example uses ExoPlayer as the foreground player. The remainder of this
guide will describe the features necessary for background audio playback of IMA
ads.

> [!IMPORTANT]
> **Key Point:** The [Basic Example](https://github.com/googleads/googleads-ima-android/tree/main/basicexample) implements the [Exoplayer-IMA extension](https://github.com/google/ExoPlayer/tree/release-v2/extensions/ima) which handles the majority of the IMA SDK's setup. Because of this, the Basic Example is not able to be used as a starting point for this guide.

## Adding background ad playback to your app

For music and audio ad playback to continue when the app is in background mode,
you can create a [`Service`
component](https://developer.android.com/guide/components/services) that contains a
custom audio player and an ad loader.

If your app has a `MainActivity` and an `AudioPlayerService` for audio playback,
you can modify your `AndroidManifest.xml` file as shown below:

    <?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>

In the service, you can create a custom audio player, which can be any media
player as long as it also implements the `VideoAdPlayer` interface for
[interacting with the IMA
SDK](https://developers.google.com/interactive-media-ads/docs/sdks/android/custom_ad_playback#interface_with_videoadplayer).

IMA SDK v. 3.16.1 added a new function,
[`createAudioAdDisplayContainer`](https://developers.google.com/interactive-media-ads/docs/sdks/android/client-side/api/reference/com/google/ads/interactivemedia/v3/api/ImaSdkFactory.md.txt#createAudioAdDisplayContainer(android.content.Context)),
to create a specialized container for an ad loader to request audio ads.

The following code snippet shows an example of the `AudioPlayerService` for
initializing and making audio ad requests.

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

## Using ads with companion ad slots

You can initialize ads with or without companion ad slots. If you choose to
render companion ads, you need to provide access of the
`AudioPlayerService` to the `MainActivity` class through a service binder as
shown below:

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

You can call the `addCompanionAdSlot()` function and pass a UI container for
rendering companion banner ads as you initialize ads from the `MainActivity`
class.

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

You can compare your implementation with the
[Audio Player Example](https://github.com/googleads/googleads-ima-android/tree/main/audioplayerexample)
if you run into issue. For farther questions on background audio ad playback,
reach out through the
[Ad Manager Help Center](https://support.google.com/admanager/contact/contact_us_ima_sdk)
for support.