Anúncios em banner

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

本指南介绍了如何将横幅广告视图集成到 Unity 应用中。除了代码段和说明之外,本指南还包含有关如何正确调整横幅广告大小的信息,以及其他资源的链接。

前提条件

Sempre teste com anúncios de teste

O exemplo de código a seguir contém um ID de bloco de anúncios que pode ser usado para solicitar anúncios de teste. Ele foi configurado especialmente para retornar anúncios de teste em vez de anúncios de produção para cada solicitação, tornando-o seguro de uso.

No entanto, depois de registrar um app na interface da WebAdMob e criar os próprios IDs de bloco de anúncios para uso no app, configure explicitamente seu dispositivo como um dispositivo de teste durante o desenvolvimento.

Android

ca-app-pub-3940256099942544/6300978111

iOS

ca-app-pub-3940256099942544/2934735716

Inicializar o SDK de anúncios para dispositivos móveis

Antes de carregar os anúncios, chame MobileAds.Initialize() para inicializar o SDK dos anúncios para dispositivos móveis no app. Isso precisa ser feito apenas uma vez, de preferência na inicialização do 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.
        });
    }
}

Se você estiver usando a mediação, aguarde até que o callback ocorra antes de carregar anúncios, já que isso garante que todos os adaptadores de mediação sejam inicializados.

BannerView 示例

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

创建横幅广告视图

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


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

  BannerView _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 BannerView(_adUnitId, AdSize.Banner, AdPosition.Top);
  }

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

  • adUnitIdBannerView 应从中加载广告的广告单元 ID。
  • AdSize:要使用的广告尺寸。有关详情,请参阅横幅广告尺寸
  • AdPosition:应放置横幅广告视图的位置。AdPosition 枚举列出了有效的广告位置值。

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

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

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

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

BannerView 的左上角位于传递给构造函数的 x 和 y 值,其中原点是屏幕的左上角。

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

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

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

加载横幅广告

要加载广告,请创建一个 AdRequest 并将其传递给 LoadAd() 方法。

/// <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)
    {
        CreateBannerView();
    }

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

    // 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 自适应高度 自适应横幅广告 手机和平板电脑 N/A
屏幕宽度 x 32|50|90 智能横幅广告 手机和平板电脑 SMART_BANNER
详细了解自适应横幅广告(旨在取代智能横幅广告)。

其他资源