插页式广告

插页式广告是全屏广告,会覆盖所在应用的整个界面。它们通常在应用流程的自然过渡点(例如游戏关卡之间的暂停时段)展示。当应用展示插页式广告时,用户可以选择点按广告,访问其目标网址,也可以将其关闭,返回应用。

本指南介绍了如何将插页式广告植入到 Unity 应用中。

前提条件

Always test with test ads

The following sample code contains an ad unit ID which you can use to request test ads. It's been specially configured to return test ads rather than production ads for every request, making it safe to use.

However, after you've registered an app in the Ad Manager web interface and created your own ad unit IDs for use in your app, explicitly configure your device as a test device during development.

/6499/example/interstitial

初始化移动广告 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.
        });
    }
}

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

实现

植入插页式广告的主要步骤如下所示:

  1. 加载插页式广告
  2. 展示插页式广告
  3. 监听插页式广告事件
  4. 清理插页式广告
  5. 预加载下一个插页式广告

加载插页式广告

插页式广告的加载是通过对 InterstitialAd 类使用静态 Load() 方法完成的。该加载方法需要使用广告单元 ID、AdManagerAdRequest 对象,以及在广告加载成功或失败时调用的完成处理程序。已加载的 AdManagerInterstitialAd 对象会以完成处理程序中的参数的形式提供。以下示例展示了如何加载 AdManagerInterstitialAd


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

  private InterstitialAd _interstitialAd;

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

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

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

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

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

              _interstitialAd = ad;
          });
  }

展示插页式广告

要展示已加载的插页式广告,请对 AdManagerInterstitialAd 实例调用 Show() 方法。广告可能会在每次加载时展示一次。使用 CanShowAd() 方法验证广告是否已做好展示准备。

/// <summary>
/// Shows the interstitial ad.
/// </summary>
public void ShowInterstitialAd()
{
    if (_interstitialAd != null && _interstitialAd.CanShowAd())
    {
        Debug.Log("Showing interstitial ad.");
        _interstitialAd.Show();
    }
    else
    {
        Debug.LogError("Interstitial ad is not ready yet.");
    }
}

监听插页式广告事件

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

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

清理插页式广告

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

_interstitialAd.Destroy();

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

预加载下一个插页式广告

插页式广告是一次性的对象。这意味着,在展示插页式广告后,就无法再使用了该对象。要请求另一个插页式广告,请创建一个新的 AdManagerInterstitialAd 对象。

如需为下一次展示机会准备好插页式广告,请在 OnAdFullScreenContentClosedOnAdFullScreenContentFailed 广告事件引发后预加载插页式广告。

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

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

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

应用事件

借助应用事件,您可以制作可向应用代码发送消息的广告。然后,应用可以根据这些消息执行操作。

您可以使用 AppEvent 监听 Ad Manager 所特有的应用事件。这些事件可能会在广告生命周期内的任何时间发生,甚至在调用加载方法之前发生。

namespace GoogleMobileAds.Api.AdManager;

/// The App event message sent from the ad.
public class AppEvent
{
    // Name of the app event.
    string Name;
    // Argument passed from the app event.
    string Value;
}

在广告中发生应用事件时,系统会引发 OnAppEventReceived。以下示例说明了如何在代码中处理此事件:

_interstitialAd.OnAppEventReceived += (AppEvent args) =>
{
    Debug.Log($"Received app event from the ad: {args.Name}, {args.Value}.");
};

以下示例展示了如何根据使用了颜色名称的应用事件更改应用的背景颜色:

_interstitialAd.OnAppEventReceived += (AppEvent args) =>
{
  if (args.Name == "color")
  {
    Color color;
    if (ColorUtility.TryParseColor(arg.Value, out color))
    {
      gameObject.GetComponent<Renderer>().material.color = color;
    }
  }
};

此外,下面是发送颜色应用事件的相应广告素材:

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

最佳实践

确定插页式广告是否适合您的应用。
在具有自然过渡点的应用中,插页式广告的效果最好。此类过渡点通常存在于应用内的任务结束时,例如分享完图片或完成一个游戏关卡时。请务必考虑应用流程中的哪些时间点展示插页式广告的效果最好,以及用户可能会如何响应。
在展示插页式广告时暂停操作。
插页式广告类型多样,包括文字广告、图片广告或视频广告等。请务必确保应用在展示插页式广告时,也会暂停使用某些资源,以便广告能够利用这些资源。例如,当您发出展示插页式广告的调用后,请务必暂停应用产生的所有音频输出。您可以在 OnAdFullScreenContentClosed() 事件中恢复声音播放,该事件会在用户结束与广告互动时调用。此外,请考虑在广告展示时暂时停止所有密集计算任务,例如游戏循环。这样可以确保用户不会遇到图像无响应、响应慢或视频卡顿的现象。
不要向用户展示太多广告。
虽然提高插页式广告在应用中的展示频次似乎是增加收入的好方法,但这么做也会影响用户体验并降低点击率。应确保用户不会频繁受到广告打扰,使他们可以充分享受到使用应用的乐趣。

其他资源