设置横幅广告

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

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

前提条件

务必用测试广告进行测试

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

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

/21775744923/example/adaptive-banner

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

如需详细了解 GMA Next-Gen SDK 测试广告如何运作,请参阅启用测试广告。

创建 AdView 对象

如需显示横幅,请执行以下操作:

Kotlin

  1. 创建一个 AdView 对象。
  2. 将 AdView 对象添加到应用的布局中。

以下示例创建了 AdView 对象并将其添加到应用布局中:

private fun createAdView(adViewContainer: FrameLayout, activity: Activity) {
  val adView = AdView(activity)
  adViewContainer.addView(adView)
}

Java

  1. 创建一个 AdView 对象。
  2. 将 AdView 对象添加到应用的布局中。

以下示例会创建 AdView 对象并将其添加到应用布局中:

private void createAdView(FrameLayout adViewContainer, Activity activity) {
  AdView adView = new AdView(activity);
  adViewContainer.addView(adView);
}

XML 布局

向布局 XML 文件中添加 AdView 元素:

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

  <com.google.android.libraries.ads.mobile.sdk.banner.AdView
      android:id="@+id/adView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Jetpack Compose

  1. 在 remember 代码块内创建一个 AdView 对象。
  2. 在 Compose 界面中添加 AndroidView 元素,以显示 AdView 对象:
val context = LocalContext.current
val adView = remember { AdView(context) }

// The AdView is placed at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  Box(modifier = modifier.fillMaxWidth()) {
    // Display the ad within an AndroidView.
    AndroidView(modifier = modifier.wrapContentSize(), factory = { adView })
  }
}

加载广告

以下示例会将一个宽度为 360 的锚定自适应横幅广告加载到 AdView 对象中:

Kotlin

private fun loadBannerAd(adView: AdView, activity: Activity) {
  // Get a BannerAdRequest for a 360 wide large anchored adaptive banner ad.
  val adSize = AdSize.getLargeAnchoredAdaptiveBannerAdSize(activity, 360)
  val adRequest = BannerAdRequest.Builder(AD_UNIT_ID, adSize).build()

  adView.loadAd(
    adRequest,
    object : AdLoadCallback<BannerAd> {
      override fun onAdLoaded(ad: BannerAd) {
        Log.d(TAG, "Banner ad loaded.")
      }

      override fun onAdFailedToLoad(adError: LoadAdError) {
        Log.d(TAG, "Banner ad failed to load: $adError")
      }
    },
  )
}

Java

private void loadBannerAd(AdView adView, Activity activity) {
  // Get a BannerAdRequest for a 360 wide large anchored adaptive banner ad.
  AdSize adSize = AdSize.getLargeAnchoredAdaptiveBannerAdSize(activity, 360);
  BannerAdRequest adRequest = new BannerAdRequest.Builder(AD_UNIT_ID, adSize).build();

  adView.loadAd(
      adRequest,
      new AdLoadCallback<BannerAd>() {
        @Override
        public void onAdLoaded(@NonNull BannerAd bannerAd) {
          Log.d(TAG, "Banner ad loaded.");
        }

        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError adError) {
          Log.d(TAG, "Banner ad failed to load: " + adError);
        }
      });
}

Jetpack Compose

// Request a large anchored adaptive banner with a width of 360.
val adSize = AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, 360)

// Load the ad when the screen is active.
val isPreviewMode = LocalInspectionMode.current
LaunchedEffect(adSize) {
  if (!isPreviewMode) {
    val adRequest = BannerAdRequest.Builder(AD_UNIT_ID, adSize).build()
    adView.loadAd(
      adRequest,
      object : AdLoadCallback<BannerAd> {
        override fun onAdLoaded(ad: BannerAd) {
          Log.d(Constant.TAG, "Banner ad loaded.")
        }

        override fun onAdFailedToLoad(adError: LoadAdError) {
          Log.w(Constant.TAG, "Banner ad failed to load: $adError")
        }
      },
    )
  }
}

刷新广告

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

释放广告资源

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

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

Kotlin

private 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

private void destroyBanner() {
  // Remove banner from view hierarchy.
  if (adView != null) {
    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 { adView.destroy() } }

广告事件

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

Kotlin

override fun onAdLoaded(ad: BannerAd) {
  ad.adEventCallback =
    object : BannerAdEventCallback {
      override fun onAdImpression() {
        // Banner ad recorded an impression.
        Log.d(TAG, "Banner ad recorded an impression.")
      }

      override fun onAdClicked() {
        // Banner ad recorded a click.
        Log.d(TAG, "Banner ad clicked.")
      }

      override fun onAdShowedFullScreenContent() {
        // Banner ad showed.
        Log.d(TAG, "Banner ad showed full screen content.")
      }

      override fun onAdDismissedFullScreenContent() {
        // Banner ad dismissed.
        Log.d(TAG, "Banner ad dismissed full screen content.")
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError
      ) {
        // Banner ad failed to show.
        Log.w(TAG, "Banner ad failed to show full screen content: $fullScreenContentError")
      }
    }
}

Java

@Override
public void onAdLoaded(@NonNull BannerAd bannerAd) {
  bannerAd.setAdEventCallback(
      new BannerAdEventCallback() {
        @Override
        public void onAdImpression() {
          // Banner ad recorded an impression.
          Log.d(TAG, "Banner ad recorded an impression.");
        }

        @Override
        public void onAdClicked() {
          // Banner ad recorded a click.
          Log.d(TAG, "Banner ad clicked.");
        }

        @Override
        public void onAdShowedFullScreenContent() {
          // Banner ad showed.
          Log.d(TAG, "Banner ad showed full screen content.");
        }

        @Override
        public void onAdDismissedFullScreenContent() {
          // Banner ad dismissed.
          Log.d(TAG, "Banner ad dismissed full screen content.");
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          // Banner ad failed to show.
          Log.w(
              TAG,
              "Banner ad failed to show full screen content: " + fullScreenContentError);
        }
      });
}

广告刷新回调

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

Kotlin

adView.loadAd(
  adRequest,
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      ad.bannerAdRefreshCallback =
        object : BannerAdRefreshCallback {
          override fun onAdRefreshed() {
            // Banner ad refreshed.
            Log.d(TAG, "Banner ad refreshed.")
          }

          override fun onAdFailedToRefresh(adError: LoadAdError) {
            // Banner ad failed to refresh.
            Log.w(TAG, "Banner ad failed to refresh: $adError")
          }
        }
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {
      // Banner ad failed to load.
      Log.w(TAG, "Banner ad failed to load: $adError")
    }
  },
)

Java

adView.loadAd(
    adRequest,
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd bannerAd) {
        bannerAd.setBannerAdRefreshCallback(
            new BannerAdRefreshCallback() {
              @Override
              public void onAdRefreshed() {
                // Banner ad refreshed.
                Log.d(TAG, "Banner ad refreshed.");
              }

              @Override
              public void onAdFailedToRefresh(@NonNull LoadAdError adError) {
                // Banner ad failed to refresh.
                Log.w(TAG, "Banner ad failed to refresh: " + adError);
              }
            });
      }

      @Override
      public void onAdFailedToLoad(@NonNull LoadAdError adError) {
        // Banner ad failed to load.
        Log.w(TAG, "Banner ad failed to load: " + adError);
      }
    });

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

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

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

下载并运行示例应用,该应用演示了如何使用 GMA Next-Gen SDK。