Anzeigen mit Prämie

所谓激励广告,指的是用户可以选择与之互动来换取应用内奖励的一种广告。本指南介绍了如何将 AdMob 激励广告植入到 Unity 应用中。

阅读一些客户成功案例:案例研究 1案例研究 2

本指南介绍了如何将激励广告植入到 Unity 应用中。

前提条件

Immer mit Testanzeigen testen

Der Beispielcode unten enthält eine Anzeigenblock-ID, mit der Sie Testanzeigen anfordern können. Es wurde speziell konfiguriert, um bei jeder Anfrage Testanzeigen anstelle von Produktionsanzeigen zurückzugeben, sodass es sicher verwendet werden kann.

Nachdem Sie jedoch eine App in derAdMob -Weboberfläche registriert und eigene Anzeigenblock-IDs zur Verwendung in Ihrer App erstellt haben, konfigurieren Sie Ihr Gerät während der Entwicklung explizit als Testgerät.

Android

ca-app-pub-3940256099942544/5224354917

iOS

ca-app-pub-3940256099942544/1712485313

Mobile Ads SDK initialisieren

Bevor die Anzeigen geladen werden, muss Ihre App das Mobile Ads SDK initialisieren. Rufen Sie dazu MobileAds.Initialize() auf. Dieser Schritt muss nur einmal durchgeführt werden, idealerweise direkt beim Start der App.

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

Wenn Sie die Vermittlung verwenden, warten Sie, bis der Callback erfolgt ist, bevor Sie die Anzeigen laden. So wird sichergestellt, dass alle Vermittlungsadapter initialisiert werden.

实现

植入激励广告的主要步骤如下所示:

  1. 加载激励广告
  2. [可选] 验证服务器端验证 (SSV) 回调
  3. 通过奖励回调展示激励广告
  4. 监听激励广告事件
  5. 清理激励广告
  6. 预加载下一个激励广告

加载激励广告

激励广告的加载是通过对 RewardedAd 类使用静态 Load() 方法完成的。已加载的 RewardedAd 对象以完成处理程序中的参数的形式提供。以下示例展示了如何加载 RewardedAd


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

  private RewardedAd _rewardedAd;

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

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

      // create our request used to load the ad.
      var adRequest = new AdRequest();

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

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

              _rewardedAd = ad;
          });
  }

[可选] 验证服务器端验证 (SSV) 回调

对于需要服务器端验证回调中额外数据的应用,应使用激励广告的自定义数据功能。在激励广告对象上设置的任何字符串值都将传递给 SSV 回调的 custom_data 查询参数。如果未设置自定义数据值,custom_data 查询参数值不会出现在 SSV 回调中。

以下代码示例演示了如何在加载激励广告后设置 SSV 选项。

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

    // If the operation completed successfully, no error is returned.
    Debug.Log("Rewarded 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 ShowRewardedAd()
{
    const string rewardMsg =
        "Rewarded ad rewarded the user. Type: {0}, amount: {1}.";

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

监听激励广告事件

若要进一步自定义您广告的行为,您可以在广告生命周期内加入许多事件,如打开、关闭等等。您可以通过注册代理来监听这些事件,如下所示。

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

清理激励广告

创建完 RewardedAd 后,请确保在放弃对它的引用前调用 Destroy() 方法:

_rewardedAd.Destroy();

这会通知插件已不再使用该对象,且可回收它占用的内存。此方法调用失败将导致内存泄漏。

预加载下一个激励广告

RewardedAd 是一次性对象。这意味着,在激励广告展示后,该对象就无法再使用了。若要再请求一个激励广告,您需要创建一个新的 RewardedAd 对象。

若要为下一次展示机会准备好激励广告,请在 OnAdFullScreenContentClosedOnAdFullScreenContentFailed 广告事件引发后预加载激励广告。

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

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

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

其他资源