插页式广告

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

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

前提条件

务必用测试广告进行测试

以下示例代码包含一个广告单元 ID,可供您用来请求测试广告。该测试广告单元 ID 已经过专门配置,可为每个请求返回测试广告(而不是实际投放的广告),因此能安全地使用。

不过,在Ad Manager 网页界面中注册了应用并创建您自己的广告单元 ID 以在应用中使用后,请在开发期间明确将您的设备配置为测试设备

/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() 事件中恢复声音播放,当用户结束与广告的互动时,就会调用以下事件。此外,请考虑在广告展示时暂停所有密集计算任务,例如游戏循环。这样可以确保用户不会遇到图像无响应、响应慢或视频卡顿的现象。
不要向用户展示太多广告。
虽然提高插页式广告在应用中的展示频次似乎是实现增收的好方法,但这么做也会影响用户体验并降低点击率。应确保用户不会频繁受到广告打扰,使他们可以充分享受到使用应用的乐趣。

其他资源