Questo documento è stato aggiornato.
La traduzione in Italiano non è ancora completa.
Aggiornamento inglese: 3 mag 2021
Aggiornamento Italiano: 31 mag 2019

Add Rewarded Video Ads to an Android App

The Audience Network allows you to monetize your Android apps with Facebook ads. Rewarded video ads are a full screen experience where users opt-in to view a video ad in exchange for something of value, such as virtual currency, in-app items, exclusive content, and more. The ad experience is 15-30 second non-skippable 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.

Prima di proseguire, assicurati di aver consultato le guide Primi passi di Audience Network e Primi passi su Android.

Step-by-Step

Step 1: Initializing Rewarded Video Ads in your Activity

Step 2: Showing Rewarded Video Ads in your Activity

Inizializzare l'SDK di Audience Network

Questo metodo è stato aggiunto nell'SDK Android Audience Network versione 5.1.

L'inizializzazione esplicita dell'SDK Audience Network per Android è obbligatoria a partire dalla versione 5.3.0. Consulta questo documento per informazioni su come inizializzare l'SDK Audience Network per Android.

Prima di creare un oggetto pubblicitario e caricare le inserzioni, devi inizializzare l'SDK di Audience Network. È consigliabile eseguire questa operazione all'avvio dell'app.

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

Step 1: Initializing Rewarded Video 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 video ad requires a RewardedVideoAdListener interface which implements the following methods in the sample code to handle various events. For example in your activity:

private final String TAG = RewardedVideoAdActivity.class.getSimpleName();
private RewardedVideoAd rewardedVideoAd;

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

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

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

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

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

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

        @Override
        public void onRewardedVideoClosed() {
            // The Rewarded Video ad was closed - this can occur during the video
            // by closing the app, or closing the end card.
            Log.d(TAG, "Rewarded video ad closed!");
        }
    };
    rewardedVideoAd.loadAd(
            rewardedVideoAd.buildLoadAdConfig()
                    .withAdListener(rewardedVideoAdListener)
                    .build());
    ...
}

Step 2: Showing Rewarded Video Ads

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

private RewardedVideoAd rewardedVideoAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    // Instantiate a RewardedVideoAd 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).
    rewardedVideoAd = new RewardedVideoAd(this, "YOUR_PLACEMENT_ID");
    RewardedVideoAdListener rewardedVideoAdListener = new RewardedVideoAdListener() {
        ...
        @Override
        public void onAdLoaded(Ad ad) {
            // Rewarded video ad is loaded and ready to be displayed  
            rewardedVideoAd.show();
        }
        ...
    };
    rewardedVideoAd.loadAd(
            rewardedVideoAd.buildLoadAdConfig()
                    .withAdListener(rewardedVideoAdListener)
                    .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.

In caso di mancata visualizzazione dell'inserzione subito dopo il caricamento, lo sviluppatore è responsabile di verificare se l'inserzione è stata ritenuta non valida. Dopo aver caricato correttamente l'inserzione, questa sarà valida per 60 minuti. Non riceverai alcun pagamento se l'inserzione visualizzata non è valida. Devi chiamare isAdInvalidated() per convalidare l'inserzione.

You should follow the idea below, but please do not copy the code into your project since it is just an example:

private RewardedVideoAd rewardedVideoAd;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    // Instantiate a RewardedVideoAd 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).
    rewardedVideoAd = new RewardedVideoAd(this, "YOUR_PLACEMENT_ID");
    RewardedVideoAdListener rewardedVideoAdListener = new RewardedVideoAdListener() {
        ...
    };
    // load the ad
    rewardedVideoAd.loadAd(
            rewardedVideoAd.buildLoadAdConfig()
                    .withAdListener(rewardedVideoAdListener)
                    .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 rewardedVideoAd has been loaded successfully
            if (rewardedVideoAd == null || !rewardedVideoAd.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 (rewardedVideoAd.isAdInvalidated()) {
                return;
            }
            rewardedVideoAd.show();
        }
    }, 1000 * 60 * 15); // Show the ad after 15 minutes
}

Se usi l'emulatore Google Android predefinito, aggiungi la riga di codice seguente prima di caricare un'inserzione di prova:
AdSettings.addTestDevice("HASHED ID");.

Usa l'ID con hash che viene visualizzato nel logcat alla prima richiesta di caricamento di un'inserzione sul dispositivo.

Genymotion e i dispositivi fisici non richiedono questo passaggio. Se desideri eseguire il test con inserzioni reali, consulta la nostra guida ai test.

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 (rewardedVideoAd != null) {
        rewardedVideoAd.destroy();
        rewardedVideoAd = null;
    }
    super.onDestroy();
}

Accelerazione hardware per le inserzioni video

Le inserzioni video in Audience Network richiedono l'abilitazione del rendering con accelerazione hardware, in caso contrario potresti visualizzare una schermata nera nelle visualizzazioni del video. Elementi a cui si applica

  • Creatività dei video nelle inserzioni native
  • Creatività dei video nelle inserzioni insterstitial
  • Inserzioni video in-stream
  • Video con premio

L'accelerazione hardware è abilitata per impostazione predefinita se il livello dell'API di destinazione è maggiore di o uguale a 14 (Ice Cream Sandwich, Android 4.0.1), ma puoi anche abilitare questa funzione in modo esplicito al livello dell'app o dell'attività.

Livello dell'app

Nel file manifest di Android, aggiungi l'attributo seguente al tag <application> per abilitare l'accelerazione hardware per tutta la tua app:

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

Livello di attività

Se vuoi abilitare la funzione solo per attività specifiche nella tua app, puoi aggiungere la funzione seguente al tag <activity> nel tuo file manifest di Android. Nell'esempio seguente, l'accelerazione hardware viene abilitata per l'elemento AudienceNetworkActivity, usato per il rendering delle inserzioni interstitial e dei video con premio:

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

Server Side Reward Validation

This is optional! You don't have to implement server side reward validation to make use of rewarded video ads. This is only required if you decide to validate rewards on your own server to improve the security by introducing a validation step at your own server. Please provide your publisher end point to your Facebook representative in order to enable this feature.

Overview

If you manage your user rewards server-side, then Facebook offers a solution for carrying this out securely by using a validation technique. Our server will communicate with a specified https endpoint to validate each ad impression and validate whether a reward should be granted.

  1. Audience Network SDK requests a rewarded video ad with the following parameters:
    • Audience Network Placement ID
    • Unique User ID - an attribute you use to identify a unique user. For example, a numeric identifier
    • Reward Value - the value of the reward you would like to grant the user. For example, 100Coins
  2. Upon video completion, the Facebook Server relays these values to your specified end point, together with the App Secret and a Unique Transaction ID.
  3. Upon receipt, the server validates the request and responds as follows:
    • 200 response: request is valid and the reward should be delivered
    • Non 200 response: request is not valid, and the reward should not be delivered.
  4. Once the video is complete, the end card is presented and one of the following events will fire.
    • onRewardServerSuccess - triggered only if a 200 response was received during step 3.
    • onRewardServerFailed - triggered if a non 200 response was received during step 3.

An example of the URL which will hit your publisher end point, from Facebook's server: https://www.your_end_point.com/?token=APP_SECRET&puid=USER_ID&pc=REWARD_ID&ptid=UNIQUE_TRANSACTION_ID

The workflow will look like this:

Implementation

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:

private RewardedVideoAd rewardedVideoAd;

private void loadRewardedVideoAd { 
    // Instantiate a RewardedVideoAd 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).
    rewardedVideoAd = new RewardedVideoAd(this, "YOUR_PLACEMENT_ID");
    RewardedVideoAdListener rewardedVideoAdListener = new RewardedVideoAdListener() {
        ...
    };

    // Create the rewarded ad data
    RewardData rewardData = new RewardData("YOUR_USER_ID", "YOUR_REWARD");

    rewardedVideoAd.loadAd(
            rewardedVideoAd.buildLoadAdConfig()
                    .withAdListener(rewardedVideoAdListener)
                    .withRewardData(rewardData)
                    .build());
}

In order for your app to be notified whether the reward was validated or not, you will need to implement the S2SRewardedVideoAdListener interface. This includes all of the events noted above in the RewardedVideoAdListener interface, as well as two additional events. The following can be used alongise the events monetioned above.

@Override
public void onRewardServerSuccess() {
    // Rewarded video ad validated
}

@Override
public void onRewardServerFailed() {
    // Rewarded video ad not validated or no response from server  
}  

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

Next Steps