横幅广告

横幅广告视图是指在屏幕上占据一处位置的矩形图片或文字广告。用户与应用互动时,这类广告会停留在屏幕上,并且可在一段时间后自动刷新。如果您是刚开始接触移动广告的新手,横幅广告是您的绝佳选择。

本指南介绍了如何将横幅广告视图集成到 Unity 应用中。除了代码段和说明之外,本指南还介绍了如何正确调整横幅广告的尺寸,并提供了其他资源的链接。

前提条件

务必用测试广告进行测试

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

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

/6499/example/banner

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

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

BannerView 示例

以下示例代码详细介绍了如何使用横幅广告视图。在本例中,您将创建横幅广告视图的实例,使用 AdManagerAdRequest 将广告加载到横幅广告视图中,然后通过处理生命周期事件来扩展其功能。

创建横幅广告视图

若要使用横幅广告视图,第一步是在附加到 GameObject 的 C# 脚本中创建横幅广告视图的实例。


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

  AdManagerBannerView _bannerView;

  /// <summary>
  /// Creates a 320x50 banner view at top of the screen.
  /// </summary>
  public void CreateBannerView()
  {
      Debug.Log("Creating banner view");

      // If we already have a banner, destroy the old one.
      if (_bannerView != null)
      {
          DestroyAd();
      }

      // Create a 320x50 banner at top of the screen
      _bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
  }

AdManagerBannerView 的构造函数包含以下参数:

  • adUnitId:广告单元 ID,AdManagerBannerView 应通过该 ID 加载广告。
  • AdSize:要使用的广告尺寸。如需了解详情,请参阅横幅广告尺寸
  • AdPosition:应放置横幅广告视图的位置。AdPosition 枚举列出了有效的广告位置值。

请注意,您需要根据平台选择使用不同的广告单元。在 iOS 设备上发出广告请求时,您需要使用 iOS 广告单元,而在 Android 设备上发出请求时,您需要使用 Android 广告单元。

(可选)创建采用自定义位置的横幅广告视图

为了更好地控制 AdManagerBannerView 在屏幕上的位置(而不是 AdPosition 值提供的位置),请使用带有 x 坐标和 y 坐标参数的构造函数:

// Create a 320x50 banner views at coordinate (0,50) on screen.
_bannerView = new AdManagerBannerView(_adUnitId, AdSize.Banner, 0, 50);

AdManagerBannerView 的左上角会放置在传递给构造函数的 x 值和 y 值所确定的位置,原点则是屏幕的左上角。

(可选)创建采用自定义尺寸的横幅广告视图

除了使用 AdSize 常量之外,您还可以为广告指定自定义尺寸:

// Use the AdSize argument to set a custom size for the ad.
AdSize adSize = new AdSize(250, 250);
_bannerView = new AdManagerBannerView(_adUnitId, adSize, AdPosition.Bottom);

(可选)多种广告尺寸

Ad Manager 允许您在 AdManagerBannerView 中指定多个可能符合投放条件的广告尺寸。在 SDK 中实现此功能之前,请先创建一个订单项,并定位到与不同尺寸广告素材相关联的相同广告单元。

在您的应用中,将多个 AdSize 形参传递到 ValidAdSizes 中:

var adView = new AdManagerBannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
adView.ValidAdSizes = new List<AdSize>
{
    AdSize.Banner, new AdSize(120, 20), new AdSize(250, 250),
};

如果 AdManagerAdView 在刷新时更改了尺寸,您的布局应该能够自动适应新的尺寸。AdManagerAdView 默认为在第一个参数中传递的尺寸,直到返回下一个广告。

加载横幅广告

AdManagerBannerView 放置好后,继续使用 AdManagerBannerView 类中的 LoadAd() 方法加载广告。它需要一个 AdManagerAdRequest 参数,其中包含运行时信息,如定位信息、排除标签和发布商提供的 ID。

/// <summary>
/// Creates the banner view and loads a banner ad.
/// </summary>
public void LoadAd()
{
    // create an instance of a banner view first.
    if(_bannerView == null)
    {
        CreateAdManagerBannerView();
    }

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

    // send the request to load the ad.
    Debug.Log("Loading banner ad.");
    _bannerView.LoadAd(adRequest);
}

监听横幅广告视图事件

若要自定义您广告的行为,您可以在广告生命周期内加入许多事件,例如加载、打开或关闭。如需监听这些事件,请注册代理:

/// <summary>
/// listen to events the banner view may raise.
/// </summary>
private void ListenToAdEvents()
{
    // Raised when an ad is loaded into the banner view.
    _bannerView.OnBannerAdLoaded += () =>
    {
        Debug.Log("Banner view loaded an ad with response : "
            + _bannerView.GetResponseInfo());
    };
    // Raised when an ad fails to load into the banner view.
    _bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
    {
        Debug.LogError("Banner view failed to load an ad with error : "
            + error);
    };
    // Raised when the ad is estimated to have earned money.
    _bannerView.OnAdPaid += (AdValue adValue) =>
    {
        Debug.Log(String.Format("Banner view paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    _bannerView.OnAdImpressionRecorded += () =>
    {
        Debug.Log("Banner view recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    _bannerView.OnAdClicked += () =>
    {
        Debug.Log("Banner view was clicked.");
    };
    // Raised when an ad opened full screen content.
    _bannerView.OnAdFullScreenContentOpened += () =>
    {
        Debug.Log("Banner view full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    _bannerView.OnAdFullScreenContentClosed += () =>
    {
        Debug.Log("Banner view full screen content closed.");
    };
}

销毁横幅广告视图

使用完横幅广告视图后,请务必调用 Destroy() 以释放资源。

/// <summary>
/// Destroys the banner view.
/// </summary>
public void DestroyBannerView()
{
    if (_bannerView != null)
    {
        Debug.Log("Destroying banner view.");
        _bannerView.Destroy();
        _bannerView = null;
    }
}

大功告成!您的应用现在就可以展示横幅广告了。

下表列出了标准横幅广告尺寸。

尺寸(宽 x 高,以 dp 为单位) 说明 可用性 AdSize 常量
320x50 标准横幅广告 手机和平板电脑 BANNER
320x100 大型横幅广告 手机和平板电脑 LARGE_BANNER
300x250 IAB 中矩形 手机和平板电脑 MEDIUM_RECTANGLE
468x60 IAB 全尺寸横幅广告 平板电脑 FULL_BANNER
728x90 IAB 页首横幅广告 平板电脑 LEADERBOARD
提供的宽度 x 自适应高度 自适应横幅广告 手机和平板电脑 不适用
屏幕宽度 x 32|50|90 智能横幅广告 手机和平板电脑 SMART_BANNER
详细了解自适应横幅广告(旨在取代智能横幅广告)。

应用事件

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

您可以使用 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。以下示例说明了如何在代码中处理此事件:

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

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

_bannerview.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>

其他资源