本指南說明如何在 Android 應用程式中載入錨定式自動調整橫幅廣告。
必要條件
- 完成入門指南的步驟。
一律使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非實際的正式廣告。否則帳戶可能會遭到停權。
如要載入測試廣告,最簡單的方法是使用 Android 橫幅專用的測試廣告單元 ID:
/21775744923/example/adaptive-banner
測試 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 UI 中加入
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 會套用您在 Ad Manager UI 指定的重新整理頻率。如果您未啟用重新整理功能,請發出新請求。如要進一步瞭解廣告單元的重新整理功能,例如怎麼設定重新整理頻率,請參閱「行動應用程式中廣告的重新整理頻率」。
釋出廣告資源
放送完橫幅廣告後,您可以釋出橫幅廣告的資源。
如要釋出廣告資源,請從檢視區塊階層移除廣告,並捨棄所有參照項目:
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("/21775744923/example/adaptive-banner", 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("/21775744923/example/adaptive-banner", 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("/21775744923/example/adaptive-banner", 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("/21775744923/example/adaptive-banner", 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 類別,建議您啟用這項功能。
啟用硬體加速功能
如果啟用全域硬體加速,會使應用程式無法正常運作,可針對個別活動啟用這項功能。如要啟用或停用硬體加速,請在 AndroidManifest.xml 中,針對 <application> 和 <activity> 元素使用 android:hardwareAccelerated 屬性。請參考以下範例,為整個應用程式啟用硬體加速,但對特定活動停用該功能:
<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>
請參閱硬體加速指南,進一步瞭解硬體加速的控管選項。請注意,如果活動沒有啟用硬體加速功能,就無法為個別廣告檢視區塊啟用,因此活動必須啟用硬體加速。
請下載並執行範例應用程式,瞭解如何使用 GMA Next-Gen SDK。