横幅广告

请选择平台Android iOS Unity Flutter

横幅广告是占据应用部分布局的矩形广告。锚定自适应横幅广告是固定宽高比的广告,当用户与应用互动时,横幅广告会停留在屏幕上(锚定在屏幕顶部或底部)。

本指南介绍了如何将自适应锚定横幅广告加载到 Android 应用中。

前提条件

务必用测试广告进行测试

在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被中止。

对于 Android 横幅广告,加载测试广告最简便的方法就是使用下面的专用测试广告单元 ID:

/21775744923/example/adaptive-banner

该测试广告单元 ID 已经过专门配置,可确保每个请求返回的都是测试广告。您可以在自己应用的编码、测试和调试过程中使用该测试广告单元 ID。只需确保您会在发布应用前用自己的广告单元 ID 替换该测试广告单元 ID 即可。

如需详细了解 Google 移动广告 SDK 测试广告的工作原理,请参阅启用测试广告

定义广告视图

XML 布局

向布局 XML 文件中添加一个视图,用作锚定自适应横幅广告的容器:

<!-- Ad view container that fills the width of the screen and adjusts its
    height to the content of the ad. -->
<FrameLayout
        android:id="@+id/ad_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true" />

Jetpack Compose

  1. 添加 JetpackComposeDemo/compose-util 模块。此模块包含用于组合 AdView 对象和素材资源的辅助程序。

  2. compose-util 模块中组合一个 BannerAd 类:


// Place the ad view at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  Box(modifier = modifier.fillMaxWidth()) { AdManagerBannerAd(adView, modifier) }
}

设置广告尺寸

AdSize 设置为具有指定宽度的锚定型自适应横幅广告类型:

Java

// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360));

Kotlin

// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360))

Jetpack Compose


// Set the adaptive banner ad size with a given width.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(LocalContext.current, 360)
adView.setAdSize(adSize)

向布局中添加 AdManagerAdView

使用广告尺寸创建 AdManagerAdView 以添加到应用的布局中:

Java


// Create a new ad view.
adView = new AdManagerAdView(this);
adView.setAdUnitId(AD_UNIT);
// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360));

// Replace ad container with new ad view.
adContainerView.removeAllViews();
adContainerView.addView(adView);

Kotlin


// Create a new ad view.
val adView = AdManagerAdView(this)
adView.adUnitId = AD_UNIT_ID
// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360))
this.adView = adView

// Replace ad container with new ad view.
binding.adViewContainer.removeAllViews()
binding.adViewContainer.addView(adView)

Jetpack Compose


val adView = remember { AdManagerAdView(context) }

// Setup and load the adview.
// Set the unique ID for this specific ad unit.
adView.adUnitId = ADMANANGER_ADAPTIVE_BANNER_AD_UNIT_ID

// Set the adaptive banner ad size with a given width.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(LocalContext.current, 360)
adView.setAdSize(adSize)

// Place the ad view at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  Box(modifier = modifier.fillMaxWidth()) { AdManagerBannerAd(adView, modifier) }
}

加载广告

AdManagerAdView 放置好后,下一步是加载广告。广告加载是使用 AdManagerAdView 类中的 loadAd() 方法完成的。此方法需要一个 AdManagerAdRequest 参数,该参数中包含关于单个广告请求的运行时信息(如定位信息)。

以下示例展示了如何加载广告:

Java

AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
adView.loadAd(adRequest);

Kotlin

val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)

如果成功,您的应用就可以展示横幅广告了。

刷新广告

如果您已将广告单元配置为定期刷新,则当广告加载失败时,无需再请求另一个广告。 Google 移动广告 SDK 会按照您在 Ad Manager 界面中指定的频率进行刷新。如果您尚未启用刷新,请发出新的请求。如需详细了解广告单元刷新(例如设置刷新频率),请参阅移动应用内广告的刷新频率

发布广告资源

使用完横幅广告后,您可以释放横幅广告的资源。

如需释放广告的资源,请从视图层次结构中移除广告并舍弃其所有引用:

Java

public void destroyBanner() {
  // Remove banner from view hierarchy.
  if (adView != null) {
    View parentView = (View) adView.getParent();
    if (parentView instanceof ViewGroup) {
      ((ViewGroup) parentView).removeView(adView);
    }

    // Destroy the banner ad resources.
    adView.destroy();
  }

  // Drop reference to the banner ad.
  adView = null;
}

Kotlin

fun destroyBanner() {
  // Remove banner from view hierarchy.
  val parentView = adView?.parent
  if (parentView is ViewGroup) {
    parentView.removeView(adView)
  }

  // Destroy the banner ad resources.
  adView?.destroy()

  // Drop reference to the banner ad.
  adView = null
}

广告事件

您可以监听广告生命周期中的许多事件,包括加载、广告展示和点击,以及广告打开和关闭事件。建议在加载横幅之前设置回调。

Java

if (adView != null) {
  adView.setAdListener(
      new AdListener() {
        @Override
        public void onAdClicked() {
          // Code to be executed when the user clicks on an ad.
        }

        @Override
        public void onAdClosed() {
          // Code to be executed when the user is about to return
          // to the app after tapping on an ad.
        }

        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError adError) {
          // Code to be executed when an ad request fails.
        }

        @Override
        public void onAdImpression() {
          // Code to be executed when an impression is recorded
          // for an ad.
        }

        @Override
        public void onAdLoaded() {
          // Code to be executed when an ad finishes loading.
        }

        @Override
        public void onAdOpened() {
          // Code to be executed when an ad opens an overlay that
          // covers the screen.
        }
      });
}

Kotlin

adView?.adListener =
  object : AdListener() {
    override fun onAdClicked() {
      // Code to be executed when the user clicks on an ad.
    }

    override fun onAdClosed() {
      // Code to be executed when the user is about to return
      // to the app after tapping on an ad.
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {
      // Code to be executed when an ad request fails.
    }

    override fun onAdImpression() {
      // Code to be executed when an impression is recorded
      // for an ad.
    }

    override fun onAdLoaded() {
      // Code to be executed when an ad finishes loading.
    }

    override fun onAdOpened() {
      // Code to be executed when an ad opens an overlay that
      // covers the screen.
    }
  }

AdListener 中每种可替换的方法均对应广告生命周期内的一个事件。

可替换的方法
onAdClicked() 记录了广告获得的点击后,系统会调用 onAdClicked() 方法。
onAdClosed() 用户在查看广告的目标网址后返回应用时,系统会调用 onAdClosed() 方法。应用可以使用此方法恢复暂停的活动,或执行任何其他必要的操作,以做好互动准备。
onAdFailedToLoad() onAdFailedToLoad() 是唯一包含参数的方法。LoadAdError 类型的 error 参数描述了发生的错误。如需了解详情,请参阅“调试广告加载错误”文档
onAdImpression() 记录了广告获得的展示后,系统会调用 onAdImpression() 方法。
onAdLoaded() 广告加载完成后,系统会执行 onAdLoaded() 方法。如果您想推迟给 activity 或 fragment 添加 AdManagerAdView 的操作,例如推迟到您确定广告会加载时,可以在此处进行。
onAdOpened() 广告打开覆盖屏幕的叠加层时,系统会调用 onAdOpened() 方法。

针对视频广告启用硬件加速

为了确保视频广告在横幅广告视图中成功展示,必须启用硬件加速

硬件加速默认处于启用状态,但有些应用可能会选择将其停用。如果您的应用停用了硬件加速,我们建议您为使用广告的 Activity 类启用硬件加速。

启用硬件加速功能

如果您的应用在全局级别启用硬件加速时无法正常运行,您也可以针对个别 activity 启用或停用硬件加速。如需启用或停用硬件加速,您可以针对 AndroidManifest.xml 中的 <application><activity> 元素使用 android:hardwareAccelerated 属性。以下示例展示了如何为整个应用启用硬件加速,但为一个 activity 停用硬件加速:

<application android:hardwareAccelerated="true">
    <!-- For activities that use ads, hardwareAcceleration should be true. -->
    <activity android:hardwareAccelerated="true" />
    <!-- For activities that don't use ads, hardwareAcceleration can be false. -->
    <activity android:hardwareAccelerated="false" />
</application>

如需详细了解用于控制硬件加速的选项,请参阅硬件加速指南。请注意,如果针对 activity 停用了硬件加速,那么将无法针对单个广告视图启用,因此必须针对 activity 本身启用硬件加速。

手动统计展示次数

手动统计展示次数功能仅适用于直销型广告系列和自家广告系列,且这些广告系列中的广告素材直接在 Ad Manager 中进行投放管理。它不应该用于补余广告或第三方广告联盟广告。如需了解详情,请参阅统计展示次数和点击次数

对于应在何时记录展示次数,如果您有特殊的条件,可手动向 Ad Manager 发送展示 ping:

Java

if (adManagerAdView != null) {
  adManagerAdView.setManualImpressionsEnabled(true);
}

Kotlin

adManagerAdView?.setManualImpressionsEnabled(true)

当您确定广告已成功返回并展示在屏幕上时,您可以手动记录一次展示:

Java

if (adManagerAdView != null) {
  adManagerAdView.recordManualImpression();
}

Kotlin

adManagerAdView?.recordManualImpression()

应用事件

借助应用事件,您可以在制作广告时加入向应用代码发送消息的功能,以便应用根据这些消息进行操作。

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

AdManagerAdView 上设置 AppEventListener

Java

if (adManagerAdView != null) {
  adManagerAdView.setAppEventListener(this);
}

Kotlin

adManagerAdView?.appEventListener = this

下面的示例显示了如何根据带颜色名称的应用事件更改应用的背景颜色:

Java

@Override
public void onAppEvent(@NonNull String name, @NonNull String info) {
  if (name.equals("color")) {
    switch (info) {
      case "green":
        // Set background color to green.
        break;
      case "blue":
        // Set background color to blue.
        break;
      default:
        // Set background color to black.
        break;
    }
  }
}

Kotlin

override fun onAppEvent(name: String, info: String) {
  if (name == "color") {
    when (info) {
      "green" -> {
        // Set background color to green.
      }
      "blue" -> {
        // Set background color to blue.
      }
      else -> {
        // Set background color to black.
      }
    }
  }
}

另外,下面是向监听器发送颜色应用事件消息的相应广告素材:

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

有关 API Demo 应用中应用事件的实现方式,请参阅 Ad Manager 应用事件示例。

Java Kotlin JetpackCompose

后续步骤

折叠式横幅广告

折叠式横幅广告是一种横幅广告,最初会以较大的叠加层形式展示,并提供一个可将广告收起为较小尺寸的按钮。不妨考虑使用它来进一步优化效果。如需了解详情,请参阅折叠式横幅广告

内嵌自适应横幅广告

与锚定自适应横幅广告相比,内嵌自适应横幅广告是一种更大、更高的横幅广告。这种广告的高度可调整,最高可与设备屏幕一样高。 对于在可滚动内容中放置横幅广告的应用,建议使用内嵌自适应横幅广告,而不是锚定自适应横幅广告。如需了解详情,请参阅内嵌自适应横幅

浏览其他主题