本指南說明如何在 Android 應用程式中載入錨定式自動調整橫幅廣告。
必要條件
- 完成入門指南的步驟。
一律使用測試廣告進行測試
建構及測試應用程式時,請務必使用測試廣告,而非實際的正式廣告。否則帳戶可能會遭到停權。
如要載入測試廣告,最簡單的方法是使用 Android 橫幅專用的測試廣告單元 ID:
ca-app-pub-3940256099942544/9214589741
這類 ID 經特別設定,可針對每個請求傳回測試廣告。您可在編寫程式碼、測試及偵錯時,將其用於自己的應用程式。發布應用程式前,請務必將測試用 ID 替換為自己的廣告單元 ID。
如要進一步瞭解 Google Mobile Ads 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 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()) },
)
}
}
}
載入廣告
- 使用廣告單元 ID 和錨定自動調整廣告大小,建立
BannerAdRequest
物件。 - 呼叫
BannerAd.load()
。 - 將
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 Mobile Ads SDK (Beta 版) 會套用您在 AdMob 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("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
類別,建議您啟用這項功能。
啟用硬體加速功能
如果啟用全域硬體加速,會使應用程式無法正常運作,可針對個別活動啟用這項功能。如要啟用或停用硬體加速,請在 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>
請參閱硬體加速指南,進一步瞭解硬體加速的控管選項。請注意,如果活動沒有啟用硬體加速功能,就無法為個別廣告檢視區塊啟用,因此活動必須啟用硬體加速。
請下載並執行範例應用程式,瞭解如何使用 Google Mobile Ads SDK (Beta 版)。