リワード インタースティシャル広告

リワード インタースティシャルは、アプリの画面が切り替わる自然なタイミングで自動的に表示される広告に対して報酬を提供できる、インセンティブ広告フォーマットの一種です。リワード広告とは異なり、ユーザーはリワード インタースティシャルを表示するためにオプトインする必要はありません。

前提条件

テストは必ずテスト広告で行う

以下のサンプルコードには、テスト広告のリクエストに使用できる広告ユニット ID が含まれています。この ID は、どのリクエストに対しても実際の広告ではなくテスト広告を返すように設定されており、安全に使用できます。

ただし、AdMob ウェブ インターフェースにアプリを登録し、アプリで使用する独自の広告ユニット ID を作成した後は、開発中に明示的にデバイスをテストデバイスとして設定する必要があります。

Android

ca-app-pub-3940256099942544/5354046379

iOS

ca-app-pub-3940256099942544/6978759866

Mobile Ads SDK を初期化する

広告を読み込む前に MobileAds.Initialize() を呼び出して、アプリで Mobile Ads SDK を初期化します。この処理は 1 回だけ行います(アプリの起動時に行うのが理想的です)。

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 クエリ パラメータに渡されます。カスタムデータ値が設定されていない場合、custom_data クエリ パラメータ値は SSV コールバックに含まれません。

次のコード例は、リワード インタースティシャル広告の読み込み後に 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);
        
});

カスタム リワード文字列を設定する場合は、広告を表示する前に行う必要があります。

リワード インタースティシャル広告を報酬のコールバック付きで表示する

広告を表示する際には、ユーザーへの報酬を処理するコールバックを指定する必要があります。読み込んだ広告は 1 回だけ表示できます。広告を表示する準備ができていることを確認するには、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 オブジェクトを読み込む必要があります。

次のインプレッションの機会に備えてリワード インタースティシャル広告を用意するには、広告イベント OnAdFullScreenContentClosed または 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();
    };
}

参考情報