전면 광고

Interstitial ads are full-screen ads that cover the interface of their host app. They're typically displayed at natural transition points in the flow of an app, such as during the pause between levels in a game. When an app shows an interstitial ad, the user has the choice to either tap on the ad and continue to its destination or close it and return to the app.

This guide explains how to integrate interstitial ads into a Unity app.

Prerequisites

务必用测试广告进行测试

以下示例代码包含一个广告单元 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.
        });
    }
}

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

Implementation

The main steps to integrate interstitial ads are:

  1. Load the interstitial ad
  2. Show the interstitial ad
  3. Listen to interstitial ad events
  4. Clean up the interstitial ad
  5. Preload the next interstitial ad

Load the interstitial ad

Loading an interstitial ad is accomplished using the static Load() method on the InterstitialAd class. The load method requires an ad unit ID, an AdManagerAdRequest object, and a completion handler which gets called when ad loading succeeds or fails. The loaded AdManagerInterstitialAd object is provided as a parameter in the completion handler. The example below shows how to load an 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;
          });
  }

Show the interstitial ad

To show a loaded interstitial ad, call the Show() method on the AdManagerInterstitialAd instance. Ads may be shown once per load. Use the CanShowAd() method to verify that the ad is ready to be shown.

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

Listen to interstitial ad events

To further customize the behavior of your ad, you can hook into a number of events in the ad's lifecycle. Listen for these events by registering a delegate as shown below.

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

Clean up the interstitial ad

When you are finished with an AdManagerInterstitialAd, make sure to call the Destroy() method before dropping your reference to it:

_interstitialAd.Destroy();

This notifies the plugin that the object is no longer used and the memory it occupies can be reclaimed. Failure to call this method results in memory leaks.

Preload the next interstitial ad

Interstitial ads are a one-time-use object. This means once an interstitial ad is shown, the object can't be used again. To request another interstitial ad, create a new AdManagerInterstitialAd object.

To prepare an interstitial ad for the next impression opportunity, preload the interstitial ad once the OnAdFullScreenContentClosed or OnAdFullScreenContentFailed ad event is raised.

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>

Best practices

Determine whether interstitial ads are the right type of ad for your app.
Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, such as sharing an image or completing a game level, creates such a point. Make sure you consider at which points in your app's flow to best display interstitial ads and how the user is likely to respond.
Pause the action when displaying an interstitial ad.
There are a number of different types of interstitial ads such as text, image, or video. It's important to make sure that when your app displays an interstitial ad, it also suspends its use of some resources to allow the ad to take advantage of them. For example, when you make the call to display an interstitial ad, be sure to pause any audio output being produced by your app. You can resume playing sounds in the OnAdFullScreenContentClosed() event, which can be invoked when the user has finished interacting with the ad. In addition, consider temporarily halting any intense computation tasks, such as a game loop, while the ad is being displayed. This ensures that the user doesn't experience slow or unresponsive graphics or stuttered video.
Don't flood the user with ads.
While increasing the frequency of interstitial ads in your app might seem like a great way to increase revenue, it can also degrade the user experience and lower click-through rates. Make sure that users aren't so frequently interrupted that they're no longer able to enjoy the use of your app.

Additional resources