Add Rewarded Interstitial Ads to an Android App

The Audience Network allows you to monetize your Android apps with Facebook ads. Rewarded interstitial ads are a full screen experience which starts when users reach a natural break in a game, and which offers rewards in exchange for a user viewing the full ad. Users can opt-out at any time. The ad experience is 15-30 seconds and contains an end card with a call to action. Upon completion of the full video, you will receive a callback to grant the suggested reward to the user.

Asegúrate de haber completado las guías de primeros pasos de Audience Network y Android antes de continuar.

Step-by-Step

Step 1: Initializing Rewarded Interstitial Ads in your Activity

Step 2: Showing Rewarded Interstitial Ads in your Activity

Inicializar el SDK de Audience Network

Este método se añadió en la versión 5.1 del SDK de Audience Network para Android.

La inicialización explícita del SDK de Audience Network para Android es necesaria para la versión 5.3.0 y versiones posteriores. Consulta este documento, que contiene información sobre cómo inicializar el SDK de Audience Network para Android.

Antes de crear un objeto publicitario y cargar anuncios, debes inicializar el SDK de Audience Network. Te recomendamos que lo hagas al iniciar la aplicación.

public class YourApplication extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize the Audience Network SDK
        AudienceNetworkAds.initialize(this);       
    }
    ...
}

Step 1: Initializing Rewarded Interstitial Ads in your Activity

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

import com.facebook.ads.*;

Then, initialize the rewarded video object, set the listener and load the video creative. The rewarded ad requires a RewardedInterstitialAdListener interface which implements the following methods in the sample code to handle various events. For example in your activity:

private final String TAG = YourActivity.class.getSimpleName();
    private RewardedInterstitialAd rewardedInterstitialAd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        // Instantiate a RewardedInterstitialAd 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).
        rewardedInterstitialAd = new RewardedInterstitialAd(this, "YOUR_PLACEMENT_ID");
        RewardedInterstitialAdListener rewardedInterstitialAdListener =
            new RewardedInterstitialAdListener() {
                @Override
                public void onError(Ad ad, AdError error) {
                    // Rewarded interstitial ad failed to load
                    Log.e(TAG, "Rewarded interstitial ad failed to load: " + error.getErrorMessage());
                }

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

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

                @Override
                public void onLoggingImpression(Ad ad) {
                    // Rewarded Interstitial ad impression - the event will fire when the 
                    // interstitial starts playing
                    Log.d(TAG, "Rewarded interstitial ad impression logged!");
                }

                @Override
                public void onRewardedInterstitialCompleted() {
                    // Rewarded Interstitial View Complete - the interstitial has been played to the end.
                    // You can use this event to initialize your reward
                    Log.d(TAG, "Rewarded interstitial completed!");

                    // Call method to give reward
                    // giveReward();
                }

                @Override
                public void onRewardedInterstitialClosed() {
                    // The Rewarded Interstitial ad was closed - this can occur during the interstitial
                    // by closing the app, or closing the end card.
                    Log.d(TAG, "Rewarded interstitial ad closed!");
                }
            };
        rewardedInterstitialAd.loadAd(
                rewardedInterstitialAd.buildLoadAdConfig()
                        .withAdListener(rewardedInterstitialAdListener)
                        .build());

        ...
    }
}  

Step 2: Showing Rewarded Interstitial Ads

Scenario 1: Immediately display the ad once it is loaded successfully. Modify the onAdLoaded() method above to display it as follows:

private RewardedInterstitialAd rewardedInterstitialAd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        // Instantiate a RewardedInterstitialAd 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).
        rewardedInterstitialAd = new RewardedInterstitialAd(this, "YOUR_PLACEMENT_ID");
        RewardedInterstitialAdListener rewardedInterstitialAdListener =
            new RewardedInterstitialAdListener() {
                ...
                @Override
                public void onAdLoaded(Ad ad) {
                    // Rewarded interstitial ad is loaded and ready to be displayed  
                    Log.d(TAG, "Rewarded interstitial ad is loaded and ready to be displayed!");
                    rewardedInterstitialAd.show(
                        rewardedInterstitialAd.buildShowAdConfig()
                            .withAppOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .build());
                }
                ...
            };

        rewardedInterstitialAd.loadAd(
                rewardedInterstitialAd.buildLoadAdConfig()
                        .withAdListener(rewardedInterstitialAdListener)
                        .build());

        ...
}

Scenario 2: Display the ad in a few seconds or minutes after it is successfully loaded. You should check whether the ad has been invalidated before displaying it.

En caso de que el anuncio no se muestre inmediatamente una vez se haya cargado, el desarrollador será responsable de comprobar si ha quedado invalidado o no. Una vez se cargue correctamente, el anuncio será válido durante 60 minutos. No recibirás pagos si muestras un anuncio invalidado. Para validar el anuncio, debes llamar al método isAdInvalidated().

Follow the code below, but do not copy the code into your project since this is for example purposes only:

private RewardedInterstitialAd rewardedInterstitialAd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        // Instantiate a RewardedInterstitialAd 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).
        rewardedInterstitialAd = new RewardedInterstitialAd(this, "YOUR_PLACEMENT_ID");
        RewardedInterstitialAdListener rewardedInterstitialAdListener =
                new RewardedInterstitialAdListener() {
                    ...
                };
        rewardedInterstitialAd.loadAd(
                rewardedInterstitialAd.buildLoadAdConfig()
                        .withAdListener(rewardedInterstitialAdListener)
                        .build());
    
        // Here is just an example for displaying the ad with delay
        // Please call this method at appropriate timing in your project
        showAdWithDelay();
    }

    private void showAdWithDelay() {
        /*
         * Here is an example for displaying the ad with delay;
         * Please do not copy the Handler into your project
         */
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                // Check if rewardedInterstitialAd has been loaded successfully
                if (rewardedInterstitialAd == null || !rewardedInterstitialAd.isAdLoaded()) {
                    return;
                }
                // Check if ad is already expired or invalidated, and do not show ad if that is the
                // case. You will not get paid to show an invalidated ad.
                if (rewardedInterstitialAd.isAdInvalidated()) {
                    return;
                }
                rewardedInterstitialAd.show(
                        rewardedInterstitialAd.buildShowAdConfig()
                                .withAppOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .build()
                );
            }
        }, 1000 * 60 * 15); // Show the ad after 15 minutes
    }

Si usas el emulador predeterminado de Android de Google, debes añadir esta línea de código antes de cargar un anuncio de prueba:
AdSettings.addTestDevice("HASHED ID");.

Utiliza el identificador con hash que figura en el logcat la primera vez que realices una solicitud para cargar un anuncio en un dispositivo.

Este paso no es necesario si se utiliza el emulador Genymotion o dispositivos físicos. Si quieres realizar pruebas con anuncios reales, consulta nuestra guía para pruebas.

Finally, clean up the object with its destroy method in your activity's onDestroy method. Note that you should also use the destroy method to clean up old ad objects before assigning it to a new instance to avoid memory leak.

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

Aceleración por hardware para anuncios con vídeo

Para evitar la posibilidad de que se muestre una pantalla en negro al reproducir los anuncios con vídeo de Audience Network, es necesario activar la renderización con aceleración por hardware. Este requerimiento se aplica a:

  • contenido de vídeo en anuncios nativos,
  • contenido de vídeo en intersticiales,
  • anuncios en vídeos in-stream,
  • vídeos con premio.

La aceleración por hardware se activa de forma predeterminada si la versión de la API a la que te diriges es la 14 o posterior (Ice Cream Sandwich, Android 4.0.1), pero también puedes activarla de forma explícita en el nivel de la aplicación o de la actividad.

Nivel de la aplicación

En el archivo de manifiesto de Android, añade el siguiente atributo a la etiqueta <application> para activar la aceleración por hardware en toda la aplicación:

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

Nivel de la actividad

Si solo quieres activar la función para determinadas actividades de la aplicación, puedes añadir la siguiente función a la etiqueta <activity> en el archivo de manifiesto de Android. En el siguiente ejemplo, se muestra cómo activar la aceleración por hardware para la actividad AudienceNetworkActivity, que se utiliza para mostrar anuncios intersticiales y vídeos con premio:

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

Server Side Reward Validation

To make sure your app is notified whether the reward was validated or not, implement the S2SRewardedInterstitialAdListener interface.

This includes all of the events noted above in the RewardedInterstitialAdListener interface, as well as two additional events.

After initializing the rewarded video object, you will need to pass in a User ID and Reward amount into the rewarded ad data before loading an ad. Both User ID and Reward amount are strings. For example:

public void loadRewardedInterstitial() {
        // Instantiate a RewardedInterstitialAd object. 
        rewardedInterstitialAd = new RewardedInterstitialAd(this, "YOUR_PLACEMENT_ID");
        
        // Implement S2SRewardedInterstitialAdListener instead of RewardedInterstitialAdListener
        RewardedInterstitialAdListener rewardedInterstitialAdListener =
                new S2SRewardedInterstitialAdListener() {
                    @Override
                    public void onRewardServerFailed() {
                        // Rewarded interstitial ad reward not validated or no response from server
                        Log.d(TAG, "Rewarded interstitial ad reward validation failed");
                    }

                    @Override
                    public void onRewardServerSuccess() {
                        // Rewarded interstitial ad reward validated server side
                        Log.d(TAG, "Rewarded interstitial ad reward validated!");
                    }
                    // Other methods from RewardedInterstitialAdListener
                    ...
                };
        // Instantiate RewardData object and include in load config
        RewardData rewardData = new RewardData("YOUR_USER_ID", "YOUR_REWARD");
        rewardedInterstitialAd.loadAd(
                rewardedInterstitialAd.buildLoadAdConfig()
                        .withRewardData(rewardData)
                        .withAdListener(rewardedInterstitialAdListener)
                        .build());
   
    }

Please note - the server validation callbacks might occur after the end card has been dismissed by a user. Do not deallocate the rewarded interstitial object until after one of these callbacks.

Siguientes pasos