橫幅廣告

選取平台: Android iOS Unity Flutter

橫幅廣告是佔用應用程式版面一部分的矩形廣告。錨定自動調整橫幅廣告是固定顯示比例的廣告,會在使用者與應用程式互動時,固定顯示在畫面頂端或底部。

本指南將說明如何將錨定自動調整橫幅廣告載入 Android 應用程式。

必要條件

一律使用測試廣告進行測試

建構及測試應用程式時,請務必使用測試廣告,而非實際的正式版廣告。否則可能導致帳戶遭到停權。

如要載入測試廣告,最簡單的方法是使用 Android 橫幅廣告專用的測試廣告單元 ID:

/21775744923/example/adaptive-banner

這項廣告單元已特別設定為針對每項要求傳回測試廣告,您可以在編寫程式碼、測試及偵錯時,在自己的應用程式中使用這項廣告單元。只要確定在發布應用程式前已將其替換為自己的廣告單元 ID,即可。

如要進一步瞭解 Google Mobile Ads SDK 的測試廣告運作方式,請參閱「啟用測試廣告」。

定義廣告檢視畫面

XML 版面配置

在版面配置 XML 檔案中新增檢視畫面,做為錨定自適應橫幅廣告的容器:

<!-- Ad view container that fills the width of the screen and adjusts its
    height to the content of the ad. -->
<FrameLayout
        android:id="@+id/ad_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true" />

Jetpack Compose

  1. 步驟一:加入 JetpackComposeDemo/compose-util 模組。這個模組包含用於組合 AdView 物件和資產的輔助程式。

  2. 步驟二:使用 compose-util 模組編寫 BannerAd 類別:


// Place the ad view at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  Box(modifier = modifier.fillMaxWidth()) { AdManagerBannerAd(adView, modifier) }
}

設定廣告大小

AdSize 設為錨定自動調整橫幅廣告類型,並指定寬度:

Java

// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360));

Kotlin

// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360))

Jetpack Compose


// Set the adaptive banner ad size with a given width.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(LocalContext.current, 360)
adView.setAdSize(adSize)

在版面配置中新增 AdManagerAdView

使用廣告大小建立 AdManagerAdView,並新增至應用程式的版面配置:

Java

// Create a new ad view.
adView = new AdManagerAdView(this);
adView.setAdUnitId(AD_UNIT);
// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360));

// Replace ad container with new ad view.
adContainerView.removeAllViews();
adContainerView.addView(adView);

Kotlin

// Create a new ad view.
val adView = AdManagerAdView(this)
adView.adUnitId = AD_UNIT_ID
// Request an anchored adaptive banner with a width of 360.
adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 360))
this.adView = adView

// Replace ad container with new ad view.
binding.adViewContainer.removeAllViews()
binding.adViewContainer.addView(adView)

Jetpack Compose


val adView = remember { AdManagerAdView(context) }

// Setup and load the adview.
// Set the unique ID for this specific ad unit.
adView.adUnitId = ADMANANGER_ADAPTIVE_BANNER_AD_UNIT_ID

// Set the adaptive banner ad size with a given width.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(LocalContext.current, 360)
adView.setAdSize(adSize)

// Place the ad view at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
  Box(modifier = modifier.fillMaxWidth()) { AdManagerBannerAd(adView, modifier) }
}

載入廣告

AdManagerAdView 就位後,下一步就是載入廣告。您可以使用 AdManagerAdView 類別中的 loadAd() 方法完成這項操作。這個方法會採用 AdManagerAdRequest 參數,該參數會儲存單一廣告請求的執行階段資訊,例如指定目標資訊。

以下範例說明如何載入廣告:

Java

AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder().build();
adView.loadAd(adRequest);

Kotlin

val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)

如果成功,您的應用程式就能顯示橫幅廣告。

重新整理廣告

如果您已將廣告單元設為重新整理,廣告載入失敗時,您就不需要要求其他廣告。Google Mobile Ads SDK 會遵循您在 Ad Manager 使用者介面中指定的任何重新整理頻率。如果您尚未啟用重新整理功能,請發出新的要求。如要進一步瞭解廣告單元重新整理作業 (例如設定重新整理頻率),請參閱「行動應用程式中廣告的重新整理頻率」。

釋出廣告資源

使用橫幅廣告完畢後,您可以釋放橫幅廣告的資源。

如要釋放廣告資源,請從檢視區塊階層中移除廣告,並放棄所有參照:

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


DisposableEffect(Unit) {
  // Destroy the AdView to prevent memory s when the screen is disposed.
  onDispose { adView.destroy() }
}

廣告事件

您可以在廣告的生命週期中監聽多個事件,包括載入、廣告曝光和點擊,以及廣告開啟和關閉事件。建議您在載入橫幅廣告前設定回呼。

Java

adView.setAdListener(new AdListener() {
    @Override
    public void onAdClicked() {
      // Code to be executed when the user clicks on an ad.
    }

    @Override
    public void onAdClosed() {
      // Code to be executed when the user is about to return
      // to the app after tapping on an ad.
    }

    @Override
    public void onAdFailedToLoad(LoadAdError adError) {
      // Code to be executed when an ad request fails.
    }

    @Override
    public void onAdImpression() {
      // Code to be executed when an impression is recorded
      // for an ad.
    }

    @Override
    public void onAdLoaded() {
      // Code to be executed when an ad finishes loading.
    }

    @Override
    public void onAdOpened() {
      // Code to be executed when an ad opens an overlay that
      // covers the screen.
    }
});

Kotlin

adView.adListener = object: AdListener() {
    override fun onAdClicked() {
      // Code to be executed when the user clicks on an ad.
    }

    override fun onAdClosed() {
      // Code to be executed when the user is about to return
      // to the app after tapping on an ad.
    }

    override fun onAdFailedToLoad(adError : LoadAdError) {
      // Code to be executed when an ad request fails.
    }

    override fun onAdImpression() {
      // Code to be executed when an impression is recorded
      // for an ad.
    }

    override fun onAdLoaded() {
      // Code to be executed when an ad finishes loading.
    }

    override fun onAdOpened() {
      // Code to be executed when an ad opens an overlay that
      // covers the screen.
    }
}

AdListener 中的每個可覆寫方法都對應至廣告生命週期中的事件。

可覆寫的方法
onAdClicked()系統會在記錄廣告點擊時叫用 onAdClicked() 方法。
onAdClosed()當使用者在瀏覽廣告的到達網址後返回應用程式時,系統會叫用 onAdClosed() 方法。應用程式可使用此方法繼續執行已暫停的活動,或執行其他必要作業,以便準備好進行互動。
onAdFailedToLoad()onAdFailedToLoad() 方法是唯一包含參數的方法。LoadAdError 類型的錯誤參數會說明發生的錯誤。詳情請參閱廣告載入錯誤偵錯說明文件
onAdImpression()系統會在記錄廣告曝光時叫用 onAdImpression() 方法。
onAdLoaded()廣告載入完成後,系統會執行 onAdLoaded() 方法。如果您想延後將 AdManagerAdView 新增至活動或片段,直到您確定廣告會載入為止,例如,您可以在此處執行此操作。
onAdOpened()廣告開啟覆蓋畫面的重疊時,系統會叫用 onAdOpened() 方法。

影片廣告的硬體加速功能

如要讓影片廣告順利顯示在橫幅廣告檢視畫面中,請務必啟用硬體加速功能。

系統預設會啟用硬體加速功能,但部分應用程式可能會選擇停用。如果這項規定適用於您的應用程式,建議您為使用廣告的 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>

如要進一步瞭解控制硬體加速功能的選項,請參閱「硬體加速指南」。請注意,如果活動已停用,則無法為個別廣告檢視畫面啟用硬體加速功能,因此活動本身必須已啟用硬體加速功能。

以人工方式計算曝光次數

手動計算曝光功能只適用於直接銷售和內部廣告活動,且廣告素材必須直接在 Ad Manager 中投放。不應用於候補廣告或第三方聯播網廣告。詳情請參閱「計算曝光和點擊次數」。

如果您有特殊條件,可決定何時記錄曝光,可以手動傳送曝光呼叫給 Ad Manager。如要這樣做,請在載入廣告前為手動曝光啟用 AdManagerAdRequest

Java

AdManagerAdRequest adRequest = new AdManagerAdRequest.Builder()
    .setManualImpressionsEnabled(true)
    .build();

Kotlin

val adRequest = AdManagerAdRequest.Builder()
    .setManualImpressionsEnabled(true)
    .build()

確定廣告已成功傳回並顯示在畫面上後,您可以手動記錄曝光:

Java

AdManagerAdView.recordManualImpression();

Kotlin

AdManagerAdView.recordManualImpression()

應用程式事件

應用程式事件可讓您建立廣告,將訊息傳送至應用程式程式碼。應用程式就能根據這些訊息採取行動。

您可以使用 AppEventListener 監聽 Ad Manager 特定應用程式事件。這些事件可在廣告生命週期中的任何時間發生,甚至在呼叫 onAdLoaded() 之前。

Java

public interface AppEventListener {
  void onAppEvent(String name, String info);
}

Kotlin

interface AppEventListener {
    fun onAppEvent(name: String, info: String)
}

當廣告中發生應用程式事件時,系統會呼叫 void onAppEvent(String name, String info)。這個介面可由活動或任何其他物件實作:

Java

import com.google.android.gms.ads.admanager.*;

public class BannerExample extends Activity implements AppEventListener {
}

Kotlin

import com.google.android.gms.ads.admanager.*

class BannerExample : Activity(), AppEventListener {
}

然後傳遞至 AdManagerAdView

Java

AdManagerAdView.setAppEventListener(this);

Kotlin

AdManagerAdView.appEventListener = this

以下範例說明如何根據名稱為 color 的應用程式事件變更應用程式的背景顏色:

Java

@Override
public void onAppEvent(String name, String info) {
  if ("color".equals(name)) {
    if ("green".equals(info)) {
      // Set background color to green.
    } else if ("blue".equals(info)) {
      // Set background color to blue.
    } else {
      // Set background color to black.
    }
  }
}

Kotlin

override fun onAppEvent(name: String?, info: String?) {
    if (name == "color") {
        when (info) {
            "green" -> {
                // Set background color to green.
            }
            "blue" -> {
                // Set background color to blue.
            }
            else -> {
                // Set background color to black.
            }
        }
    }
}

以下是傳送顏色應用程式事件訊息至事件監聽器的對應廣告素材:

<html>
<head>
  <script src="//www.gstatic.com/afma/api/v1/google_mobile_app_ads.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      // Send a color=green event when ad loads.
      admob.events.disAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.disAppEvent("color", "blue");
      });
    });
  </script>
  <style>
    #ad {
      width: 320px;
      height: 50px;
      top: 0px;
      left: 0px;
      font-size: 24pt;
      font-weight: bold;
      position: absolute;
      background: black;
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
  <div id="ad">Carpe diem!</div>
</body>
</html>

如要瞭解如何在 API 示範應用程式中導入應用程式事件,請參閱 Ad Manager 應用程式事件範例。

Java Kotlin JetpackCompose

其他資源

上的範例

後續步驟

可收合橫幅廣告

可收合橫幅廣告是一開始會以較大重疊廣告顯示的橫幅廣告,並提供按鈕將廣告收合為較小的尺寸。建議您使用這項功能進一步提升成效。詳情請參閱「可收合橫幅廣告」。

內嵌自動調整橫幅廣告

相較於錨定自動調整橫幅廣告,內嵌自動調整橫幅廣告的尺寸更大、高度更高。可調整高度,甚至可與裝置螢幕一樣高。如果應用程式在可捲動內容中刊登橫幅廣告,建議使用內嵌自動調整橫幅廣告,而非錨定自動調整橫幅廣告。詳情請參閱「內嵌式自適應橫幅」。

探索其他主題