插頁式獎勵廣告

插頁式獎勵廣告是一種獎勵廣告格式,可讓您針對在應用程式自然轉換期間自動顯示的廣告提供獎勵。與獎勵廣告不同的是,插頁式獎勵廣告不需要等使用者觀看即可使用。

必要條件

一律使用測試廣告進行測試

以下程式碼範例內含用來請求測試廣告的廣告單元 ID。已設為針對每個請求傳回測試廣告,而非實際廣告,因此安全無虞。

不過,當您在AdMob 網頁介面中註冊應用程式,並自行建立要在應用程式中使用的廣告單元 ID 後,請在開發期間明確將裝置設定為測試裝置

Android

ca-app-pub-3940256099942544/5354046379

iOS

ca-app-pub-3940256099942544/6978759866

初始化 Mobile Ads SDK

載入廣告之前,請呼叫 MobileAds.Initialize(),讓應用程式初始化 Mobile Ads 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.
        });
    }
}

如果您使用中介服務,請等到回呼執行後再載入廣告,這麼做可確保所有中介服務轉接程式都已初始化。

導入作業

整合插頁式獎勵廣告的主要步驟如下:

  1. 載入插頁式獎勵廣告
  2. [選用] 驗證伺服器端驗證 (SSV) 回呼
  3. 顯示插頁式獎勵廣告及獎勵回呼
  4. 監聽插頁式獎勵廣告事件
  5. 清除插頁式獎勵廣告
  6. 預先載入下一則插頁式獎勵廣告

載入插頁式獎勵廣告

系統會使用 RewardedInterstitialAd 類別上的靜態 Load() 方法載入插頁式獎勵廣告。載入方法需要廣告單元 ID、AdRequest 物件和完成處理常式,以便在廣告載入成功或失敗時呼叫。系統會在完成處理常式中,提供已載入的 RewardedInterstitialAd 物件做為參數。以下範例說明如何載入 RewardedInterstitialAd


  // These ad units are configured to always serve test ads.
#if UNITY_ANDROID
  private string _adUnitId = "ca-app-pub-3940256099942544/5354046379";
#elif UNITY_IPHONE
  private string _adUnitId = "ca-app-pub-3940256099942544/6978759866";
#else
  private string _adUnitId = "unused";
#endif

  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 AdRequest();
      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;
          });
  }

[選用] 驗證伺服器端驗證 (SSV) 回呼

如果應用程式在伺服器端驗證回呼中需要額外資料,則應使用插頁式獎勵廣告的自訂資料功能。獎勵廣告物件上設定的任何字串值都會傳遞至 SSV 回呼的 custom_data 查詢參數。如未設定自訂資料值,SSV 回呼就不會納入 custom_data 查詢參數值。

以下程式碼範例示範如何在載入插頁式獎勵廣告後,設定 SSV 選項。

// 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);
        
});

如果您要設定自訂獎勵字串,就必須在顯示廣告前完成指定。

顯示插頁式獎勵廣告及獎勵回呼

展示廣告時,您必須提供回呼來處理使用者的獎勵。每次載入時只能顯示廣告一次。請使用 CanShowAd() 方法確認廣告已準備好顯示。

以下程式碼是顯示獎勵廣告的最佳方法。

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));
        });
    }
}

監聽插頁式獎勵廣告事件

如要進一步自訂廣告行為,您可以捕捉廣告生命週期中的多個事件。請註冊委派代表,以便監聽這些事件,如下所示。

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);
    };
}

清除插頁式獎勵廣告

完成 RewardedInterstitialAd 後,務必先呼叫 Destroy() 方法,再放置參照:

_rewardedInterstitialAd.Destroy();

這會通知外掛程式,該物件已無法使用,且可收回物件佔用的記憶體。如未呼叫此方法,可能造成記憶體流失。

預先載入下一則插頁式獎勵廣告

RewardedInterstitialAd 是一次性的物件。換言之,當獎勵廣告顯示後,該物件就無法再使用。如要請求其他插頁式獎勵廣告,您必須載入新的 RewardedInterstitialAd 物件。

為了讓插頁式獎勵廣告為下一次曝光商機做好準備,請在 OnAdFullScreenContentClosedOnAdFullScreenContentFailed 廣告事件發生後預先載入插頁式獎勵廣告。

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();
    };
}

其他資源