Interstitiel avec récompense (bêta)

L'interstitiel avec récompense est un type de format d'annonce incitatif qui vous permet d'offrir des récompenses pour les annonces qui s'affichent automatiquement lors des transitions naturelles de l'application. Contrairement aux annonces avec récompense, les utilisateurs ne sont pas obligés d'activer l'affichage d'un interstitiel avec récompense.

Conditions préalables

Implémentation

Voici les principales étapes à suivre pour intégrer des annonces interstitielles avec récompense:

  • Charger une annonce
  • S'inscrire pour recevoir des rappels d'événements en plein écran
  • Gérer le rappel de la récompense
  • Affichez l'annonce
  • [Facultatif] Valider les rappels de validation côté serveur

Charger une annonce

Le chargement d'une annonce s'effectue à l'aide de la méthode statique load() sur la classe RewardedInterstitialAd. La méthode de chargement nécessite un contexte, l'ID de votre bloc d'annonces, un objet AdRequest et une RewardedInterstitialAdLoadCallback pour être averti lorsque le chargement de l'annonce réussit ou échoue. L'objet RewardedInterstitialAd chargé est fourni en tant que paramètre dans le rappel onRewardedInterstitialAdLoaded().

L'exemple suivant montre comment charger un RewardedInterstitialAd dans votre MainActivity.

Java

public class MainActivity extends AppCompatActivity {
  private RewardedInterstitialAd rewardedInterstitialAd;
  private String TAG = "MainActivity";

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

    new Thread(
            () -> {
              // Initialize the Google Mobile Ads SDK on a background thread.
              MobileAds.initialize(this, initializationStatus -> {});
              // Load an ad on the main thread.
              runOnUiThread(
                  () -> {
                    loadAd();
                  });
            })
        .start();
  }

  public void loadAd() {
    // Use the test ad unit ID to load an ad.
    RewardedInterstitialAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
        new AdRequest.Builder().build(),  new RewardedInterstitialAdLoadCallback() {
      @Override
      public void onAdLoaded(RewardedInterstitialAd ad) {
        Log.d(TAG, "Ad was loaded.");
        rewardedInterstitialAd = ad;
      }
      @Override
      public void onAdFailedToLoad(LoadAdError loadAdError) {
        Log.d(TAG, loadAdError.toString());
        rewardedInterstitialAd = null;
      }
    });
  }
}

Kotlin

import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAd
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback

class MainActivity : AppCompactActivity() {

  private var rewardedInterstitialAd? = null
  private final var TAG = "MainActivity"

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val backgroundScope = CoroutineScope(Dispatchers.IO)
    backgroundScope.launch {
      // Initialize the Google Mobile Ads SDK on a background thread.
      MobileAds.initialize(this@MainActivity) {}
      // Load an ad on the main thread.
      runOnUiThread {
        loadAd()
      }
    }
  }

  private fun loadAd() {
    RewardedInterstitialAd.load(this, "ca-app-pub-3940256099942544/5354046379",
      AdRequest.Builder().build(), object : RewardedInterstitialAdLoadCallback() {
      override fun onAdLoaded(ad: RewardedInterstitialAd) {
        Log.d(TAG, "Ad was loaded.")
        rewardedInterstitialAd = ad
      }

      override fun onAdFailedToLoad(adError: LoadAdError) {
        Log.d(TAG, adError?.toString())
        rewardedInterstitialAd = null
      }
    })
  }
}

S'inscrire pour recevoir des rappels

Afin de recevoir des notifications pour les événements de présentation, vous devez transmettre un objet FullScreenContentCallback au setter de votre annonce. L'objet FullScreenContentCallback gère les rappels lorsque la présentation de l'annonce aboutit ou non, et lorsqu'elle est ignorée. Le code suivant montre comment définir un objet FullScreenContentCallback anonyme dans votre RewardedInterstitialAdLoadCallback:

Java

public void loadAd(){
  RewardedInterstitialAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
      new AdRequest.Builder().build(), new RewardedInterstitialAdLoadCallback() {
    @Override
    public void onAdLoaded(RewardedInterstitialAd ad) {
      rewardedInterstitialAd = ad;
      rewardedInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
        @Override
        public void onAdClicked() {
          // Called when a click is recorded for an ad.
          Log.d(TAG, "Ad was clicked.");
        }

        @Override
        public void onAdDismissedFullScreenContent() {
          // Called when ad is dismissed.
          // Set the ad reference to null so you don't show the ad a second time.
          Log.d(TAG, "Ad dismissed fullscreen content.");
          rewardedInterstitialAd = null;
        }

        @Override
        public void onAdFailedToShowFullScreenContent(AdError adError) {
          // Called when ad fails to show.
          Log.e(TAG, "Ad failed to show fullscreen content.");
          rewardedInterstitialAd = null;
        }

        @Override
        public void onAdImpression() {
          // Called when an impression is recorded for an ad.
          Log.d(TAG, "Ad recorded an impression.");
        }

        @Override
        public void onAdShowedFullScreenContent() {
          // Called when ad is shown.
          Log.d(TAG, "Ad showed fullscreen content.");
        }
      });
    }
    @Override
    public void onAdFailedToLoad(LoadAdError loadAdError) {
      Log.d(TAG, loadAdError.toString());
      rewardedInterstitialAd = null;
    }
  });
}

Kotlin

private fun loadAd() {
  RewardedInterstitialAd.load(this, "ca-app-pub-3940256099942544/5354046379",
    AdRequest.Builder().build(), object : RewardedInterstitialAdLoadCallback() {
    override fun onAdLoaded(ad: RewardedInterstitialAd) {
      rewardedInterstitialAd = ad
      rewardedInterstitialAd?.fullScreenContentCallback = object: FullScreenContentCallback() {
        override fun onAdClicked() {
          // Called when a click is recorded for an ad.
          Log.d(TAG, "Ad was clicked.")
        }

        override fun onAdDismissedFullScreenContent() {
          // Called when ad is dismissed.
          // Set the ad reference to null so you don't show the ad a second time.
          Log.d(TAG, "Ad dismissed fullscreen content.")
          rewardedInterstitialAd = null
        }

        override fun onAdFailedToShowFullScreenContent(adError: AdError) {
          // Called when ad fails to show.
          Log.e(TAG, "Ad failed to show fullscreen content.")
          rewardedInterstitialAd = null
        }

        override fun onAdImpression() {
          // Called when an impression is recorded for an ad.
          Log.d(TAG, "Ad recorded an impression.")
        }

        override fun onAdShowedFullScreenContent() {
          // Called when ad is shown.
          Log.d(TAG, "Ad showed fullscreen content.")
        }
      }
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {
      Log.d(TAG, adError?.toString())
      rewardedInterstitialAd = null
    }
  })
}

Gérer les récompenses

Pour diffuser votre annonce interstitielle avec récompense, implémentez l'interface OnUserEarnedRewardListener dans votre MainActivity. Vous serez ainsi averti lorsque l'utilisateur gagnera une récompense.

Java

public class MainActivity extends AppCompatActivity implements OnUserEarnedRewardListener {
  ...
  @Override
  public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
    Log.i(TAG, "User earned reward.");
    // TODO: Reward the user!
  }
}

Kotlin

class MainActivity : AppCompatActivity(), OnUserEarnedRewardListener {
  ...
  override fun onUserEarnedReward(rewardItem: RewardItem) {
    Log.d(TAG, "User earned reward.")
    // TODO: Reward the user!
  }
}

Diffuser l'annonce

Après avoir implémenté l'interface OnUserEarnedRewardListener, vous pouvez présenter l'annonce à l'aide de la méthode show() de l'annonce comme suit:

Java

rewardedInterstitialAd.show(/* Activity */ MainActivity.this,/*
    OnUserEarnedRewardListener */ MainActivity.this);

Kotlin

rewardedInterstitialAd?.show(/* Activity */ this, /*
    OnUserEarnedRewardListener */ this)

[Facultatif] Valider les rappels de validation côté serveur (SSV)

Les applications qui nécessitent des données supplémentaires dans les rappels de validation côté serveur doivent utiliser la fonctionnalité de données personnalisées des annonces avec récompense. Toute valeur de chaîne définie sur un objet d'annonce avec récompense est transmise au paramètre de requête custom_data du rappel de validation côté serveur. Si aucune valeur de données personnalisées n'est définie, la valeur du paramètre de requête custom_data ne sera pas présente dans le rappel SSV.

L'exemple de code suivant montre comment définir des données personnalisées sur un objet d'annonce interstitielle avec récompense avant de demander une annonce.

Java

RewardedInterstitialAd.load(MainActivity.this, "ca-app-pub-3940256099942544/5354046379",
    new AdRequest.Builder().build(),  new RewardedInterstitialAdLoadCallback() {
  @Override
  public void onAdLoaded(RewardedInterstitialAd ad) {
    Log.d(TAG, "Ad was loaded.");
    rewardedInterstitialAd = ad;
    ServerSideVerificationOptions options = new ServerSideVerificationOptions
        .Builder()
        .setCustomData("SAMPLE_CUSTOM_DATA_STRING")
        .build();
    rewardedInterstitialAd.setServerSideVerificationOptions(options);
  }
  @Override
  public void onAdFailedToLoad(LoadAdError loadAdError) {
    Log.d(TAG, loadAdError.toString());
    rewardedInterstitialAd = null;
  }
});

Kotlin

RewardedInterstitialAd.load(this, "ca-app-pub-3940256099942544/5354046379",
    AdRequest.Builder().build(), object : RewardedInterstitialAdLoadCallback() {
  override fun onAdLoaded(ad: RewardedInterstitialAd) {
    Log.d(TAG, "Ad was loaded.")
    rewardedInterstitialAd = ad
    val options = ServerSideVerificationOptions.Builder()
        .setCustomData("SAMPLE_CUSTOM_DATA_STRING")
        .build()
    rewardedInterstitialAd.setServerSideVerificationOptions(options)
  }

  override fun onAdFailedToLoad(adError: LoadAdError) {
    Log.d(TAG, adError?.toString())
    rewardedInterstitialAd = null
  }
})

Si vous souhaitez définir la chaîne de récompense personnalisée, vous devez le faire avant de diffuser l'annonce.

Exemples sur GitHub

  • Exemple d'annonces interstitielles avec récompense : Java | Kotlin

Étapes suivantes

Explorez les sujets suivants: