Implementing the In-stream Video SDK for Android

In-stream Video monetization for Audience Network is available to select publishers on an invitation-only basis.

Video publishers can now use Audience Network's In-stream solution to deliver video ads to their global audience across mobile and desktop environments in pre-roll and mid-roll settings. Follow this guide to display this type of ad unit for Android-based video content. For monetizing your web video content with in-stream ads, see the Web implementation guide. For in-stream video ads within iOS mobile apps, see the iOS implementation guide. Or see a list of available types.

Requirements

Please refer to the "In-Stream Video Requirements" section of the Design Guidelines for Audience Network Ads.

Implementation

This guide will walk you through implementing in-stream video ads on Android following these steps:

Step 1: Setup Monetization Manager

Step 2: Load and Show In-stream Video Ad



Ensure you have completed the Audience Network Getting Started and Android Getting Started guides before you proceed.

Step 1: Setup Monetization Manager

In-stream Video monetization for Audience Network is available to select publishers on an invitation-only basis.

After you have been approved for Audience Network in-stream video monetization, please work with your Audience Network Account team. They will provide you details on how to:

  • Setup your Monetization Manager
  • Create Properties
  • Create Platforms
  • Create Ad Spaces
  • Create Placements
  • Enter Payment Details
  • Submit your bundle id for review

Step 2: Load and Show In-stream Video Ad

Ensure you have completed the Audience Network Getting Started and Android Getting Started guides before you proceed.

Add the following code at the top of your activity class in order to import the Facebook Ads SDK:

import com.facebook.ads.*;

Next, instantiate an InstreamVideoAdView object and make a request to load an ad. This can also be done ahead of time, to pre-cache an ad response. In place of YOUR_PLACEMENT_ID, use the id of the in-stream video placement you created earlier.

When there is no ad to show, the onError will be called with error.code set to 1001. You should detect this and return to the content.

public class InstreamVideoAdActivity extends Activity {

    private final String TAG = InstreamVideoAdActivity.class.getSimpleName();
    private LinearLayout adContainer;
    private InstreamVideoAdView adView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loadInstreamAd();
    }

    private int pxToDP(int px) {
        return (int) (px / this.getResources().getDisplayMetrics().density);
    }

    private void loadInstreamAd() {
        // Instantiate an InstreamVideoAdView object. 
        // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
        // now, while you are testing and replace it later when you have signed up.
        // While you are using this temporary code you will only get test ads and if you release
        // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
        adView = new InstreamVideoAdView(
                this,
                "YOUR_PLACEMENT_ID",
                new AdSize(
                        pxToDP(adContainer.getMeasuredWidth()),
                        pxToDP(adContainer.getMeasuredHeight()))
        );
        // set ad listener to handle events
        adView.setAdListener(new InstreamVideoAdListener() {
            @Override
            public void onError(Ad ad, AdError adError) {
                // Instream video ad failed to load
                Log.e(TAG, "Instream video ad failed to load: " + adError.getErrorMessage());
            }

            @Override
            public void onAdLoaded(Ad ad) {
                // Instream video ad is loaded and ready to be displayed
                Log.d(TAG, "Instream video ad is loaded and ready to be displayed!");

                // Race condition, load() called again before last ad was displayed
                 if(adView == null || !adView.isAdLoaded()) {
                    return;
                }
                
                // Inflate Ad into container and show it
                adContainer = findViewById(R.id.banner_container);
                adContainer.removeAllViews();
                adContainer.addView(adView);
                adView.show();
            }


            @Override
            public void onAdVideoComplete(Ad ad) {
                // Instream Video View Complete - the video has been played to the end.
                // You can use this event to continue your video playing
                Log.d(TAG, "Instream video completed!");
            }


            @Override
            public void onAdClicked(Ad ad) {
                Log.d(TAG, "Instream video ad clicked!");
            }

            @Override
            public void onLoggingImpression(Ad ad) {
                // Instream Video ad impression - the event will fire when the
                // video starts playing
                Log.d(TAG, "Instream video ad impression logged!");
            }
        });
        adView.loadAd();
    }
}

Whenever you are trying to show the ad in a few seconds or minutes after it is successfully loaded, youshould check whether the ad has been invalidated before displaying it.

In case of not showing the ad immediately after the ad has been loaded, the developer is responsible for checking whether or not the ad has been invalidated. Once the ad is successfully loaded, the ad will be valid for 60 mins. You will not get paid if you are showing an invalidated ad. You should call isAdInvalidated() to validate the ad.

public class InstreamVideoAdActivity extends Activity {

    private LinearLayout adContainer;
    private InstreamVideoAdView adView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // set up and request the ad
        loadInstreamAd();
        // show the ad with delay;
        showInstreamVideoAdWithDelay();
    }  
      
    private void loadInstreamAd() {
        // Instantiate an InstreamVideoAdView object. 
        // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
        // now, while you are testing and replace it later when you have signed up.
        // While you are using this temporary code you will only get test ads and if you release
        // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
        adView = new InstreamVideoAdView(
                this,
                "YOUR_PLACEMENT_ID",
                new AdSize(
                        pxToDP(adContainer.getMeasuredWidth()),
                        pxToDP(adContainer.getMeasuredHeight()))
        );
        // set ad listener to handle events
        adView.setAdListener(new InstreamVideoAdListener() {
           ...
        });
        // request an ad
        adView.loadAd();
    } 

    private void showInstreamVideoAdWithDelay() {  
        // Check if adView has been loaded successfully
        if (adView == null || !adView.isAdLoaded() ) {
            return;
        }
        // Check if ad is already expired or invalidated, and do not show ad if that is the case.
        if (adView.isAdInvalidated()) {
            return;
        }
        // Inflate Ad into container and show it
        adContainer = findViewById(R.id.banner_container);
        adContainer.removeAllViews();
        adContainer.addView(adView);
        adView.show();
    }

Finally, add the following code to your activity's onDestroy() function to release resources the adView use:

@Override
protected void onDestroy() {
  if (adView != null) {
    adView.destroy();
  }
  super.onDestroy();
}

When running on the simulator, test ads will be shown by default. To enable test ads on a device, add the following line of code before loading an ad: AdSettings.addTestDevice("HASHED ID");. Use the hashed ID that is printed to the log cat when you first make a request to load an ad on a device.

Hardware Acceleration for Video Ads

Videos ads in Audience Network requires the hardware accelerated rendering to be enabled, otherwise you might experience a black screen in the video views. This applies to

  • Videos creatives in Native Ads
  • Videos creatives in Interstitials
  • In-stream Video ads
  • Rewarded Videos

Hardware acceleration is enabled by default if your Target API level is >=14 (Ice Cream Sandwich, Android 4.0.1), but you can also explicitly enable this feature at the application level or activity level.

Application Level

In your Android manifest file, add the following attribute to the <application> tag to enable hardware acceleration for your entire application:

<application android:hardwareAccelerated="true" ...>

Activity Level

If you only want to enable the feature for specific activities in your application, in your Android manifest file, you can add the following feature to the <activity> tag. The following example will enable the hardware acceleration for the AudienceNetworkActivity which is used for rendering interstitial ads and rewarded videos:

<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>

Next Steps