Android developmentAndroid tutorial

How to Playing ads with ExoPlayer 2.5 Android

How to Playing ads with ExoPlayer Android

Ads playing using ExoPlayer and IMA The new ExoPlayer 2.5 release comes with a brand new extension to play ads that wraps around the Interactive Media Ads SDK (IMA). This article will help you start using the extension, and also explains some of the advantages it offers over the use of IMA directly.

Integration of the IMA extension to your current player is simple. The first step to create an extension dependency, as explained within the README. Create an ImaAdsLoader by sending in an ad tag ID for the ads you want to play. We can support ads of DoubleClick for Publishers, Google AdSense or any other VAST-compliant ad service as well as the IMA website provides examples of ad tags to test.

Next, you need to build an AdsMediaSource that wraps the content MediaSource and provides an ImaAdsLoader reference and a ViewGroup over at the top, in which the IMA will display the ad overlay’s user interface. It is identical to MediaSource composition which you may have previously used and MediaSource is the content. MediaSource is an extension of AdsMediaSource.

The final step is to manage to pause and restart the playback of ads when the app is in the background. When the app enters the background, store the content position (obtained from player.getContentPosition()). Then, release the player however, you must keep the ImaAdsLoader since it is able to keep an eye on the playback status. If the application enters the background, it will go back for the content stored and prepare the player by using the new AdsMediaSource which was built using that same ImaAdsloader. Playback of ads will resume in the same place it was left. If the Activity is destroyed, you can release the loader to remove the resources utilized by IMA.

Playing ads with ExoPlayer Android Example

Let’s Start to create a new Android project with the selected Java language.  And Sync your project after successfully syncing your project add the below dependencies in your Gradle Build.

Add Permission to your manifest file 

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

  Step 1: Add dependencies In your project Gradle.build 

dependencies {

    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'

    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.exoplayer:exoplayer-core:2.18.1'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.18.1'
    implementation 'com.google.android.exoplayer:extension-ima:2.18.1'

}

Step 2: activity_main.xml Add Exoplayer layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.exoplayer2.ui.StyledPlayerView
        android:id="@+id/player_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Step 3: Main Activity Java file Implementation. 

package com.codeplayon.exoplayerimaextension;

import androidx.multidex.MultiDex;
import android.os.Bundle;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ext.ima.ImaAdsLoader;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import android.app.Activity;
import android.net.Uri;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.ext.ima.ImaAdsLoader;
import com.google.android.exoplayer2.source.DefaultMediaSourceFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSource;
import com.google.android.exoplayer2.util.Util;

/** Main Activity. */
public class MainActivity extends Activity {

    private static final String SAMPLE_VIDEO_URL =
            "https://storage.googleapis.com/gvabox/media/samples/stock.mp4";
    private static final String SAMPLE_VAST_TAG_URL =
            "https://pubads.g.doubleclick.net/gampad/ads?iu=/21775744923/external/"
                    + "single_ad_samples&sz=640x480&cust_params=sample_ct%3Dlinear&ciu_szs=300x250%2C728x90"
                    + "&gdfp_req=1&output=vast&unviewed_position_start=1&env=vp&impl=s&correlator=";

    private StyledPlayerView playerView;
    private ExoPlayer player;
    private ImaAdsLoader adsLoader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MultiDex.install(this);

        playerView = findViewById(R.id.player_view);

        // Create an AdsLoader.
        adsLoader = new ImaAdsLoader.Builder(/* context= */ this).build();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (Util.SDK_INT > 23) {
            initializePlayer();
            if (playerView != null) {
                playerView.onResume();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Util.SDK_INT <= 23 || player == null) {
            initializePlayer();
            if (playerView != null) {
                playerView.onResume();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (Util.SDK_INT <= 23) {
            if (playerView != null) {
                playerView.onPause();
            }
            releasePlayer();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (Util.SDK_INT > 23) {
            if (playerView != null) {
                playerView.onPause();
            }
            releasePlayer();
        }
    }

    @Override
    protected void onDestroy() {
        adsLoader.release();

        super.onDestroy();
    }

    private void releasePlayer() {
        adsLoader.setPlayer(null);
        playerView.setPlayer(null);
        player.release();
        player = null;
    }

    private void initializePlayer() {
        // Set up the factory for media sources, passing the ads loader and ad view providers.
        DataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);

        MediaSource.Factory mediaSourceFactory =
                new DefaultMediaSourceFactory(dataSourceFactory)
                        .setLocalAdInsertionComponents(unusedAdTagUri -> adsLoader, playerView);

        // Create an ExoPlayer and set it as the player for content and ads.
        player = new ExoPlayer.Builder(this).setMediaSourceFactory(mediaSourceFactory).build();
        playerView.setPlayer(player);
        adsLoader.setPlayer(player);

        // Create the MediaItem to play, specifying the content URI and ad tag URI.
        Uri contentUri = Uri.parse(SAMPLE_VIDEO_URL);
        Uri adTagUri = Uri.parse(SAMPLE_VAST_TAG_URL);
        MediaItem mediaItem =
                new MediaItem.Builder()
                        .setUri(contentUri)
                        .setAdsConfiguration(new MediaItem.AdsConfiguration.Builder(adTagUri).build())
                        .build();

        // Prepare the content and ad to be played with the SimpleExoPlayer.
        player.setMediaItem(mediaItem);
        player.prepare();

        // Set PlayWhenReady. If true, content and ads will autoplay.
        player.setPlayWhenReady(false);
    }
}

Now finally run your android app and see the output to Playing ads with ExoPlayer Android.

The benefits that come with ExoPlayer IMA extension ExoPlayer IMA extension

In a typical integration with IMA, it is generally required to switch out the source of the player whenever playback changes between content and ads, which may be inefficient, and can lead to buffering.

Contrarily, with an IMA extension ExoPlayer understands how the ads timeline seamlessly connects advertisements and content, which means users will not see buffering while switching from one to the other. The player also understands the locations of midroll ads so it is able to avoid buffering and discarding extra media after the cue point for ad break which can save the battery as well as data.

Read More:-