Get Started

This guide shows you how to integrate the Interactive Media Ads SDK into a sample video player app. Download the sample video player app (without any IMA integration) from GitHub, and at the end of the exercise the app plays a video ad before playing the app's content video. This guide should take about half an hour to complete.

Prerequisites

Before you begin, you'll need the following:

  • Read through our compatibility page to make sure your intended use case is supported.
  • Android Studio 1.0 or newer
  • The Sample Video Player app which you'll use to integrate the SDK

    Download SampleVideoPlayer.zip

  • If you'd rather follow along with a finished IMA SDK integration, download BasicExample.zip or view it on GitHub.

    Downloading and running the sample video player app

    The sample video player app provides a working simple video player app for you to use as a starting point for integrating the IMA Android SDK.

    1. Download the Sample Video Player App linked above in Prerequisites and unzip.
    2. Start Android Studio and select Open an existing Android Studio project, or if Android Studio is already running, select File > New > Import Project. Then choose SampleVideoPlayer/build.gradle.
    3. Run a Gradle sync by selecting Tools > Android > Sync Project with Gradle Files.
    4. Ensure that the player app compiles and runs on a physical Android device or an Android Virtual Device using Run > Run 'app'. It's normal for the content video to take a few moments to load before playing.

    Examining the sample video player

    The sample video player doesn't contain any IMA SDK integration code yet. The sample app consists of three major parts:

    • samplevideoplayer/SampleVideoPlayer.java - A video implementation extending VideoView that has an interface for notifying listeners when the video finishes playing.
    • res/layout/fragment_video.xml - App layout XML containing SampleVideoPlayer and defining a play button.
    • videoplayerapp/MyActivity.java - This activity defines the method orientVideoDescriptionFragment to show or hide the VideoDescriptionFragment when appropriate (for example, to hide the description fragment to allow the video to go fullscreen). This file also defines VideoFragment, which sets the VideoPlayer content URL and wires the play button click event.

    Adding the IMA Android SDK to the player app

    Include Google Play services (preferably the latest version, but at least version 4.0) in your application following these instructions. You'll also include a reference to the IMA SDK. For Android Studio the integration involves the following:

    1. Add the following to your application-level build.gradle file, located at app/build.gradle:

      app/build.gradle

      dependencies {
          compile 'com.android.support:appcompat-v7:21.+'
          compile 'com.google.ads.interactivemedia.v3:interactivemedia:3.6.0'
          compile 'com.google.android.gms:play-services-ads:10.2.1'
      }
      You will need to re-sync Gradle after the previous step via Tools > Android > Sync Project with Gradle Files. If you don't already have this version of Play services, Android Studio will prompt you to Install Repository and sync project.
    2. Add the following <meta-data> code to your to AndroidManifest.xml inside the <application> tag:

      src/main/AndroidManifest.xml

      <application
              android:allowBackup="true"
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name"
              android:theme="@style/AppTheme">
          <meta-data
                  android:name="com.google.android.gms.version"
                  android:value="@integer/google_play_services_version" />
          <activity
              android:name=".MyActivity"
              …
      </application>

    Checkpoint: Your application should compile and run, but you haven't yet added UI elements or code to request and display ads. When you initialize and manipulate UI objects, you must do so on the main thread if you are using multiple threads. In Android, UI objects are not thread-safe. See Threads for more information.

    Your first ads request

    1. Add ad tag
    2. Add an entry in strings.xml to store the VAST ad tag URL.

      res/values/strings.xml

      <?xml version="1.0" encoding="utf-8"?>
          <resources>
      
          <string name="app_name">IMA Sample Video Player<string>
          <string name="action_settings">Settings<string>
          <string name="video_description">Android Promotional Video<string>
          <string name="content_url">…<string>
          <string name="ad_tag_url"><![CDATA[http://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=]]></string>
      
          </resources>

    3. Create an AdsLoader
    4. To request ads, first create an AdsLoader from the ImaSdkFactory. Then add both an AdsLoadedListener to handle ads being loaded, and an AdErrorListener to respond to loading errors. Add the following to VideoFragment.onActivityCreated():

      MyActivity.java

      
      public void onActivityCreated(Bundle bundle) {
          super.onActivityCreated(bundle);
            
          // Create an AdsLoader.
          mSdkFactory = ImaSdkFactory.getInstance();
          mAdsLoader = mSdkFactory.createAdsLoader(this.getContext());
          // Add listeners for when ads are loaded and for errors.
          mAdsLoader.addAdErrorListener(this);
          mAdsLoader.addAdsLoadedListener(new AdsLoadedListener() {
              @Override
              public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
                  // Ads were successfully loaded, so get the AdsManager instance. AdsManager has
                  // events for ad playback and errors.
                  mAdsManager = adsManagerLoadedEvent.getAdsManager();
      
                  // Attach event and error event listeners.
                  mAdsManager.addAdErrorListener(VideoFragment.this);
                  mAdsManager.addAdEventListener(VideoFragment.this);
                  mAdsManager.init();
              }
          });
      }

    5. Add completion and click listeners
    6. The video player fires a VideoCompletedListener when the content video finishes. Add a listener to notify the AdsLoader when the content finishes. Then add an OnClickListener to request ads when the play button is clicked:

      MyActivity.java

      
      public void onActivityCreated(Bundle bundle) {
          super.onActivityCreated(bundle);
      
          // Create an AdsLoader.
          ...
          });
          
          // Add listener for when the content video finishes.
          mVideoPlayer.addVideoCompletedListener(new OnVideoCompletedListener() {
              @Override
              public void onVideoCompleted() {
                  // Handle completed event for playing post-rolls.
                  if (mAdsLoader != null) {
                      mAdsLoader.contentComplete();
                  }
              }
          });
      
          // When Play is clicked, request ads and hide the button.
          mPlayButton.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  mVideoPlayer.setVideoPath(getString(R.string.content_url));
                  requestAds(getString(R.string.ad_tag_url));
                  view.setVisibility(View.GONE);
              }
          });
      }

    7. Request ads
    8. Implement the requestAds() method to create the AdsRequest. As part of the request, provide a ContentProgressProvider to inform the SDK about the content video's progress, which is used to determine when to play mid-rolls. End the function by calling AdsLoader.requestAds() to send the request.

      MyActivity.java

      
      private void requestAds(String adTagUrl) {
          AdDisplayContainer adDisplayContainer = mSdkFactory.createAdDisplayContainer();
          adDisplayContainer.setAdContainer(mAdUiContainer);
      
          // Create the ads request.
          AdsRequest request = mSdkFactory.createAdsRequest();
          request.setAdTagUrl(adTagUrl);
          request.setAdDisplayContainer(adDisplayContainer);
          request.setContentProgressProvider(new ContentProgressProvider() {
              @Override
              public VideoProgressUpdate getContentProgress() {
                  if (mIsAdDisplayed || mVideoPlayer == null || mVideoPlayer.getDuration() <= 0) {
                      return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
                  }
                  return new VideoProgressUpdate(mVideoPlayer.getCurrentPosition(),
                          mVideoPlayer.getDuration());
              }
          });
      
          // Request the ad. After the ad is loaded, onAdsManagerLoaded() will be called.
          mAdsLoader.requestAds(request);
      }

    9. Handling ad events
    10. The app must handle ad events sent from the SDK to notify it about major ad events. Implement the onAdEvent() method to handle events sent from AdsManager. Of particular importance is to call AdsManager.start() to start playing ads, and to pause and resume the content video when ads start and end.

      MyActivity.java

      
      @Override
      public void onAdEvent(AdEvent adEvent) {
          Log.i(LOGTAG, "Event: " + adEvent.getType());
      
          // These are the suggested event types to handle. For full list of all ad event
          // types, see the documentation for AdEvent.AdEventType.
          switch (adEvent.getType()) {
              case LOADED:
                  // AdEventType.LOADED will be fired when ads are ready to be played.
                  // AdsManager.start() begins ad playback. This method is ignored for VMAP or
                  // ad rules playlists, as the SDK will automatically start executing the
                  // playlist.
                  mAdsManager.start();
                  break;
              case CONTENT_PAUSE_REQUESTED:
                  // AdEventType.CONTENT_PAUSE_REQUESTED is fired immediately before a video
                  // ad is played.
                  mIsAdDisplayed = true;
                  mVideoPlayer.pause();
                  break;
              case CONTENT_RESUME_REQUESTED:
                  // AdEventType.CONTENT_RESUME_REQUESTED is fired when the ad is completed
                  // and you should start playing your content.
                  mIsAdDisplayed = false;
                  mVideoPlayer.play();
                  break;
              case ALL_ADS_COMPLETED:
                  if (mAdsManager != null) {
                      mAdsManager.destroy();
                      mAdsManager = null;
                  }
                  break;
              default:
                  break;
          }
      }

    11. Errors, pause and resume
    12. The app also needs to handle errors thrown by the SDK. Implement onAdError() to log errors and to resume content video playback if the ads can't play. Change the onPause() and onResume() methods to call AdsManager if playing an ad.

      MyActivity.java

      
      @Override
          public void onAdError(AdErrorEvent adErrorEvent) {
              Log.e(LOGTAG, "Ad Error: " + adErrorEvent.getError().getMessage());
              mVideoPlayer.play();
          }
      
          @Override
          public void onResume() {
              if (mAdsManager != null && mIsAdDisplayed) {
                  mAdsManager.resume();
              } else {
                  mVideoPlayer.play();
              }
              super.onResume();
          }
          @Override
          public void onPause() {
              if (mAdsManager != null && mIsAdDisplayed) {
                  mAdsManager.pause();
              } else {
                  mVideoPlayer.pause();
              }
              super.onPause();
          }
      }

    Congrats! You're now requesting and displaying video ads in your Android application. To fine tune your implementation, read advanced topics and the API documentation.

    Troubleshooting

    If you're experiencing issues playing a video ad, try downloading the completed BasicExample below and change the ad_tag_url defined in strings.xml to the ad tag URL you're testing with. If it works properly in the BasicExample then there's likely an issue with your app's IMA integration code. Review this guide and API docs to detect any discrepancies.

    Download BasicExample.zip View on GitHub

    Still having issues? Drop us a line on the IMA SDK forum and follow our Google+ page for other announcements and updates.

    Send feedback about...

    IMA SDK for Android
    Need help? Visit our support page.