本指南介绍了如何将锚定自适应横幅广告加载到 Android 应用中。
前提条件
- 通读入门指南。
务必用测试广告进行测试
在构建和测试应用时,请确保使用的是测试广告,而不是实际投放的广告。否则,可能会导致您的账号被中止。
对于 Android 横幅广告,加载测试广告最简便的方法就是使用我们的专用测试广告单元 ID:
ca-app-pub-3940256099942544/9214589741
该测试广告单元 ID 已经过专门配置,可确保每个请求返回的都是测试广告。您可以在自己应用的编码、测试和调试过程中使用该测试广告单元 ID。需要注意的一点是,请务必在发布应用前用您自己的广告单元 ID 替换该测试广告单元 ID。
如需详细了解 GMA Next-Gen SDK 测试广告如何运作,请参阅启用测试广告。
创建 AdView 对象
如需显示横幅,请执行以下操作:
Kotlin
- 创建一个
AdView对象。 - 将
AdView对象添加到应用的布局中。
以下示例创建了 AdView 对象并将其添加到应用布局中:
private fun createAdView(adViewContainer: FrameLayout, activity: Activity) {
val adView = AdView(activity)
adViewContainer.addView(adView)
}
Java
- 创建一个
AdView对象。 - 将
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
- 在 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()) },
)
}
}
}
加载广告
以下示例将宽度为 360 的锚定自适应横幅广告加载到 AdView 对象中:
Kotlin
private fun loadBannerAd(adView: AdView, activity: Activity) {
// Get a BannerAdRequest for a 360 wide anchored adaptive banner ad.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, 360)
val adRequest = BannerAdRequest.Builder(AD_UNIT_ID, adSize).build()
adView.loadAd(
adRequest,
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
ad.adEventCallback =
object : BannerAdEventCallback {
override fun onAdImpression() {
Log.d(TAG, "Banner ad recorded an impression.")
}
override fun onAdClicked() {
Log.d(TAG, "Banner ad clicked.")
}
}
}
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.e(TAG, "Banner ad failed to load: $adError")
}
},
)
}
Java
private void loadBannerAd(AdView adView, Activity activity) {
// Get a BannerAdRequest for a 360 wide anchored adaptive banner ad.
AdSize adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(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) {
bannerAd.setAdEventCallback(
new BannerAdEventCallback() {
@Override
public void onAdImpression() {
Log.d(TAG, "Banner ad recorded an impression.");
}
@Override
public void onAdClicked() {
Log.d(TAG, "Banner ad clicked.");
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError adError) {
Log.e(TAG, "Banner ad failed to load: " + adError);
}
});
}
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")
}
}
}
}
}
刷新广告
如果您已为广告单元配置刷新功能,则在广告加载失败时无需再请求另一个广告。GMA Next-Gen SDK 会按照您在 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 本身启用硬件加速。
下载并运行示例应用,该应用演示了如何使用 GMA Next-Gen SDK。