Interstitial con premio (beta)

Interstitial con premio è un tipo di formato dell'annuncio incentivato che ti consente di offrire premi per gli annunci che vengono visualizzati automaticamente durante le naturali transizioni delle app. A differenza degli annunci con premio, gli utenti non devono attivare la visualizzazione di un annuncio interstitial con premio.

Prerequisiti

Esegui sempre test con annunci di prova

Il seguente codice di esempio contiene un ID unità pubblicitaria che puoi utilizzare per richiedere annunci di prova. È stato configurato appositamente per restituire annunci di prova anziché annunci di produzione per ogni richiesta, pertanto è sicuro da usare.

Tuttavia, dopo aver registrato un'app nell' interfaccia web e aver creato i tuoi ID unità pubblicitaria da utilizzare nell'app, configura il dispositivo come dispositivo di prova in modo esplicito durante lo sviluppo.

Android

iOS

初始化移动广告 SDK

加载广告之前,请先调用 MobileAds.Initialize(),以便让应用初始化移动广告 SDK。此操作仅需执行一次,最好是在应用启动时执行。

using GoogleMobileAds;
using GoogleMobileAds.Api;

public class GoogleMobileAdsDemoScript : MonoBehaviour
{
    public void Start()
    {
        // Initialize the Google Mobile Ads SDK.
        MobileAds.Initialize((InitializationStatus initStatus) =>
        {
            // This callback is called once the MobileAds SDK is initialized.
        });
    }
}

如果您使用的是中介功能,请等到回调发生后再加载广告,因为这可确保初始化所有的中介适配器。

Implementazione

I passaggi principali per integrare gli annunci interstitial con premio sono:

  1. Carica l'annuncio interstitial con premio
  2. [Facoltativo] Convalida i callback di verifica lato server (SSV)
  3. Mostra l'annuncio interstitial con premio con callback del premio
  4. Ascoltare eventi di annunci interstitial con premio
  5. Pulisci l'annuncio interstitial con premio
  6. Precarica il successivo annuncio interstitial con premio

Carica l'annuncio interstitial con premio

Il caricamento di un annuncio interstitial con premio viene eseguito utilizzando il metodo Load() statico nella classe RewardedInterstitialAd. Il metodo di caricamento richiede un ID unità pubblicitaria, un oggetto AdManagerAdRequest e un gestore di completamento che viene chiamato quando il caricamento dell'annuncio va a buon fine o meno. L'oggetto RewardedInterstitialAd caricato viene fornito come parametro nel gestore di completamento. L'esempio seguente mostra come caricare un RewardedInterstitialAd.


  // This ad unit is configured to always serve test ads.
  private string _adUnitId = "/6499/example/rewarded-interstitial";

  private RewardedInterstitialAd _rewardedInterstitialAd;

  /// <summary>
  /// Loads the rewarded interstitial ad.
  /// </summary>
  public void LoadRewardedInterstitialAd()
  {
      // Clean up the old ad before loading a new one.
      if (_rewardedInterstitialAd != null)
      {
            _rewardedInterstitialAd.Destroy();
            _rewardedInterstitialAd = null;
      }

      Debug.Log("Loading the rewarded interstitial ad.");

      // create our request used to load the ad.
      var adRequest = new AdManagerAdRequest();
      adRequest.Keywords.Add("unity-admob-sample");

      // send the request to load the ad.
      RewardedInterstitialAd.Load(_adUnitId, adRequest,
          (RewardedInterstitialAd ad, LoadAdError error) =>
          {
              // if error is not null, the load request failed.
              if (error != null || ad == null)
              {
                  Debug.LogError("rewarded interstitial ad failed to load an ad " +
                                 "with error : " + error);
                  return;
              }

              Debug.Log("Rewarded interstitial ad loaded with response : "
                        + ad.GetResponseInfo());

              _rewardedInterstitialAd = ad;
          });
  }

[Facoltativo] Convalida i callback di verifica lato server (SSV)

Le app che richiedono dati aggiuntivi nei callback di verifica lato server devono utilizzare la funzionalità dei dati personalizzati degli annunci interstitial con premio. Qualsiasi valore di stringa impostato su un oggetto annuncio con premio viene trasmesso al parametro di query custom_data del callback SSV. Se non viene impostato alcun valore per i dati personalizzati, il valore del parametro di query custom_data non verrà incluso nel callback SSV.

Il seguente esempio di codice mostra come impostare le opzioni SSV dopo il caricamento dell'annuncio interstitial con premio.

// send the request to load the ad.
RewardedInterstitialAd.Load(_adUnitId,
                            adRequest,
                            (RewardedInterstitialAd ad, LoadAdError error) =>
    {
        // If the operation failed, an error is returned.
        if (error != null || ad == null)
        {
            Debug.LogError("Rewarded interstitial ad failed to load an ad " +
                           " with error : " + error);
            return;
        }

        // If the operation completed successfully, no error is returned.
        Debug.Log("Rewarded interstitial ad loaded with response : " +
                   ad.GetResponseInfo());
        
        // Create and pass the SSV options to the rewarded ad.
        var options = new ServerSideVerificationOptions
                              .Builder()
                              .SetCustomData("SAMPLE_CUSTOM_DATA_STRING")
                              .Build()
        ad.SetServerSideVerificationOptions(options);
        
});

Se vuoi impostare la stringa premio personalizzata, devi farlo prima di visualizzare l'annuncio.

Mostra l'annuncio interstitial con premio con callback del premio

Quando presenti il tuo annuncio, devi fornire un callback per gestire il premio per l'utente. Gli annunci possono essere mostrati solo una volta per caricamento. Utilizza il metodo CanShowAd() per verificare che l'annuncio sia pronto per essere pubblicato.

Il seguente codice presenta il metodo migliore per visualizzare un annuncio interstitial con premio.

public void ShowRewardedInterstitialAd()
{
    const string rewardMsg =
        "Rewarded interstitial ad rewarded the user. Type: {0}, amount: {1}.";

    if (rewardedInterstitialAd != null && rewardedInterstitialAd.CanShowAd())
    {
        rewardedInterstitialAd.Show((Reward reward) =>
        {
            // TODO: Reward the user.
            Debug.Log(String.Format(rewardMsg, reward.Type, reward.Amount));
        });
    }
}

Ascoltare eventi di annunci interstitial con premio

Per personalizzare ulteriormente il comportamento dell'annuncio, puoi collegarti a una serie di eventi del ciclo di vita dell'annuncio. Ascolta questi eventi registrando un delegato, come mostrato di seguito.

private void RegisterEventHandlers(RewardedInterstitialAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Rewarded interstitial ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Rewarded interstitial ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () =>
    {
        Debug.Log("Rewarded interstitial ad was clicked.");
    };
    // Raised when an ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Rewarded interstitial ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Rewarded interstitial ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded interstitial ad failed to open " +
                       "full screen content with error : " + error);
    };
}

Pulisci l'annuncio interstitial con premio

Quando hai finito con un RewardedInterstitialAd, assicurati di chiamare il metodo Destroy() prima di rimuovere il tuo riferimento:

_rewardedInterstitialAd.Destroy();

In questo modo viene comunicato al plug-in che l'oggetto non viene più utilizzato e che è possibile recuperare la memoria che occupa. La mancata chiamata di questo metodo determina perdite di memoria.

Precarica il successivo annuncio interstitial con premio

RewardedInterstitialAd è un oggetto monouso. Ciò significa che una volta mostrato un annuncio interstitial con premio, l'oggetto non può essere riutilizzato. Per richiedere un altro annuncio interstitial con premio, devi caricare un nuovo oggetto RewardedInterstitialAd.

Per preparare un annuncio interstitial con premio per l'opportunità successiva di impressione, precarica l'annuncio interstitial con premio una volta generato l'evento dell'annuncio OnAdFullScreenContentClosed o OnAdFullScreenContentFailed.

private void RegisterReloadHandler(RewardedInterstitialAd ad)
{
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += ()
    {
        Debug.Log("Rewarded interstitial ad full screen content closed.");

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedInterstitialAd();
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) =>
    {
        Debug.LogError("Rewarded interstitial ad failed to open " +
                       "full screen content with error : " + error);

        // Reload the ad so that we can show another as soon as possible.
        LoadRewardedInterstitialAd();
    };
}

Risorse aggiuntive