横幅广告

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

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

前提条件

务必用测试广告进行测试

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

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

ca-app-pub-3940256099942544/9214589741

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

如需详细了解 Google 移动广告 SDK(Beta 版)的测试广告如何运作,请参阅启用测试广告

定义广告视图

XML 布局

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

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <FrameLayout
      android:id="@+id/banner_view_container"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent">

  </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Jetpack Compose

在 Compose 界面中添加 AndroidView 元素,并定义一个 mutableStateOf<BannerAd?> 变量来存放横幅广告:

// Initialize required variables.
val context = LocalContext.current
var bannerAdState by remember { mutableStateOf<BannerAd?>(null) }

// The AdView is placed at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  bannerAdState?.let { bannerAd ->
    Box(modifier = Modifier.fillMaxWidth()) {
      // Display the ad within an AndroidView.
      AndroidView(
        modifier = modifier.wrapContentSize(),
        factory = { bannerAd.getView(requireActivity()) },
      )
    }
  }
}

加载广告

  1. 使用广告单元 ID 和锚定自适应广告尺寸创建 BannerAdRequest 对象。
  2. 调用 BannerAd.load()
  3. BannerAd.getView() 添加到视图层次结构中。

Kotlin

import com.google.android.libraries.ads.mobile.sdk.banner.AdSize
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError

class MainActivity : Activity() {

  private var bannerAd: BannerAd? = null
  private lateinit var binding: ActivityMainBinding
  private lateinit var adSize: AdSize
  private lateinit var bannerViewContainer: FrameLayout

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    // 320 is a placeholder value. Replace 320 with your banner container width.
    adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320)

    // Give the banner container a placeholder height to avoid a sudden layout
    // shifts when the ad loads.
    bannerViewContainer = binding.bannerViewContainer
    val bannerLayoutParams = bannerViewContainer.layoutParams
    bannerLayoutParams.height = adSize.getHeightInPixels(requireContext())
    bannerViewContainer.layoutParams = bannerLayoutParams

    // Step 1 - Create a BannerAdRequest object with ad unit ID and size.
    val adRequest = BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build()

    // Step 2 - Load the ad.
    BannerAd.load(
      adRequest,
      object : AdLoadCallback<BannerAd> {
        override fun onAdLoaded(ad: BannerAd) {
          // Assign the loaded ad to the BannerAd object.
          bannerAd = ad
          // Step 3 - Call BannerAd.getView() to get the View and add it
          // to view hierarchy on the UI thread.
          activity?.runOnUiThread {
            binding.bannerViewContainer.addView(ad.getView(requireActivity()))
          }
        }

        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
          bannerAd = null
        }
      },
    )
  }
}

Java

import com.google.android.libraries.ads.mobile.sdk.banner.AdSize;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest;
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback;
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError;

public class MainActivity extends AppCompatActivity {

  private BannerAd bannerAd;
  private ActivityMainBinding binding;
  private AdSize adSize;
  private FrameLayout bannerViewContainer;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    // 320 is a placeholder value. Replace 320 with your banner container width.
    adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320);

    // Give the banner container a placeholder height to avoid a sudden layout
    // shifts when the ad loads.
    bannerViewContainer = binding.bannerViewContainer;
    LayoutParams bannerLayoutParams = bannerViewContainer.getLayoutParams();
    bannerLayoutParams.height = adSize.getHeightInPixels(this);
    bannerViewContainer.setLayoutParams(bannerLayoutParams);

    // Step 1 - Create a BannerAdRequest object with ad unit ID and size.
    BannerAdRequest adRequest = new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741",
        adSize).build();

    // Step 2 - Load the ad.
    BannerAd.load(
        adRequest,
        new AdLoadCallback<BannerAd>() {
          @Override
          public void onAdLoaded(@NonNull BannerAd ad) {
            // Assign the loaded ad to the BannerAd object.
            bannerAd = ad;
            // Step 3 - Call BannerAd.getView() to get the View and add it
            // to view hierarchy on the UI thread.
            runOnUiThread(
                () -> binding.bannerViewContainer.addView(ad.getView(MainActivity.this)));
          }

          @Override
          public void onAdFailedToLoad(@NonNull LoadAdError adError) {
            bannerAd = null;
          }
        });
  }
}

Jetpack Compose

// Request an anchored adaptive banner with a width of 360.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), 360)

// Load the ad when the screen is active.
val coroutineScope = rememberCoroutineScope()
val isPreviewMode = LocalInspectionMode.current
LaunchedEffect(context) {
  bannerAdState?.destroy()
  if (!isPreviewMode) {
    coroutineScope.launch {
      when (val result = BannerAd.load(BannerAdRequest.Builder(AD_UNIT_ID, adSize).build())) {
        is AdLoadResult.Success -> {
          bannerAdState = result.ad
        }
        is AdLoadResult.Failure -> {
          showToast("Banner failed to load.")
          Log.w(Constant.TAG, "Banner ad failed to load: $result.error")
        }
      }
    }
  }
}

刷新广告

如果您已为广告单元配置刷新功能,则在广告加载失败时无需再请求另一个广告。Google 移动广告 SDK(Beta 版)会按照您在 AdMob 界面中指定的任何频率进行刷新。如果您尚未启用刷新功能,则需发出新的请求。如需详细了解广告单元刷新(例如如何设置刷新频率),请参阅为横幅广告使用自动刷新功能

释放广告资源

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

若要释放广告占用的资源,请从视图层次结构中移除该广告并删除其所有引用:

Kotlin

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

// Remove banner from view hierarchy.
if (adView.getParent() instanceof ViewGroup) {
  ((ViewGroup) adView.getParent()).removeView(adView);
}
// Destroy the banner ad resources.
adView.destroy();
// Drop reference to the banner ad.
adView = null;

Jetpack Compose


// Destroy the ad when the screen is disposed.
DisposableEffect(Unit) { onDispose { bannerAdState?.destroy() } }

广告事件

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

Kotlin

BannerAd.load(
  BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      ad.adEventCallback =
        object : BannerAdEventCallback {
          override fun onAdImpression() {
            // Banner ad recorded an impression.
          }

          override fun onAdClicked() {
            // Banner ad recorded a click.
          }

          override fun onAdShowedFullScreenContent() {
            // Banner ad showed.
          }

          override fun onAdDismissedFullScreenContent() {
            // Banner ad dismissed.
          }

          override fun onAdFailedToShowFullScreenContent(
            fullScreenContentError: FullScreenContentError
          ) {
            // Banner ad failed to show.
          }
        }
    }
    // ...
  }
)

Java

BannerAd.load(
    new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd ad) {
        ad.setAdEventCallback(new BannerAdEventCallback() {
          @Override
          public void onAdImpression() {
            // Banner ad recorded an impression.
          }

          @Override
          public void onAdClicked() {
            // Banner ad recorded a click.
          }

          @Override
          public void onAdShowedFullScreenContent() {
            // Banner ad showed.
          }

          @Override
          public void onAdDismissedFullScreenContent() {
            // Banner ad dismissed.
          }

          @Override
          public void onAdFailedToShowFullScreenContent(
              @NonNull FullScreenContentError fullScreenContentError) {
            // Banner ad failed to show.
          }
        });

        // ...
      }
    });

广告刷新回调

如果您为横幅广告使用自动刷新BannerAdRefreshCallback 会处理广告刷新事件。请务必在将广告视图添加到视图层次结构之前设置回调。如需详细了解广告刷新,请参阅刷新广告

Kotlin

BannerAd.load(
  BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      ad.bannerAdRefreshCallback =
        object : BannerAdRefreshCallback {
          // Set the ad refresh callbacks.
          override fun onAdRefreshed() {
            // Called when the ad refreshes.
          }

          override fun onAdFailedToRefresh(loadAdError: LoadAdError) {
            // Called when the ad fails to refresh.
          }
        }

      // ...
    }
  }
)

Java

BannerAd.load(
    new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd ad) {
        ad.setBannerAdRefreshCallback(
            // Set the ad refresh callbacks.
            new BannerAdRefreshCallback() {
              @Override
              public void onAdRefreshed() {
                // Called when the ad refreshes.
              }

              @Override
              public void onAdFailedToRefresh(@NonNull LoadAdError adError) {
                // Called when the ad fails to refresh.
              }
            });
        // ...
      }
    });

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

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

硬件加速默认处于启用状态,但有些应用可能会选择将其停用。如果您的应用停用了硬件加速,我们建议您为使用广告的 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 本身启用硬件加速。

下载并运行示例应用,该应用演示了如何使用 Google 移动广告 SDK(Beta 版)。