橫幅廣告

選取平台: Android iOS Unity Flutter

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

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

必要條件

  • 完成入門指南
  • 選用:如要查看橫幅廣告導入範例,請選取下列其中一個範例應用程式:

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

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

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

/21775744923/example/adaptive-banner

這類 ID 經特別設定,可針對每個請求傳回測試廣告。您可在編寫程式碼、測試及偵錯時,將其用於自己的應用程式。發布應用程式前,請務必將這類 ID 替換為自己的廣告單元 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 = AdManagerAdRequest.Builder().build()
adView.loadAd(adRequest)

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

重新整理廣告

如果您的廣告單元已設為會自動重新整理,當廣告載入失敗,就無需再次發送請求。Google Mobile Ads SDK 會依照您在 Ad Manager 使用者介面指定的重新整理頻率執行。若未啟用重新整理功能,則需重新發送請求。如要進一步瞭解廣告單元的重新整理功能,例如怎麼設定重新整理頻率,請參閱「行動應用程式中廣告的重新整理頻率」。

釋出廣告資源

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

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

Java

public void destroyBanner() {
  // Remove banner from view hierarchy.
  if (adView != null) {
    View parentView = (View) adView.getParent();
    if (parentView instanceof ViewGroup) {
      ((ViewGroup) parentView).removeView(adView);
    }

    // Destroy the banner ad resources.
    adView.destroy();
  }

  // Drop reference to the banner ad.
  adView = null;
}

Kotlin

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

if (adView != null) {
  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(@NonNull 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:

Java

if (adManagerAdView != null) {
  adManagerAdView.setManualImpressionsEnabled(true);
}

Kotlin

adManagerAdView?.setManualImpressionsEnabled(true)

判斷廣告已成功傳回並顯示在畫面上後,即可手動記錄曝光:

Java

if (adManagerAdView != null) {
  adManagerAdView.recordManualImpression();
}

Kotlin

adManagerAdView?.recordManualImpression()

應用程式事件

您可以利用應用程式事件,在建立廣告時加入向應用程式碼傳送訊息的功能,讓應用程式在收到訊息後採取適當動作。

如要監聽 Ad Manager 專屬的應用程式事件,請使用 AppEventListener。這類事件可能在廣告生命週期的任意時間點發生,即使是在呼叫 onAdLoaded() 前也不例外。

AdManagerAdView 上設定 AppEventListener

Java

if (adManagerAdView != null) {
  adManagerAdView.setAppEventListener(this);
}

Kotlin

adManagerAdView?.appEventListener = this

下方範例則演示如何依據名為顏色的應用程式事件,變更應用程式的背景顏色:

Java

@Override
public void onAppEvent(@NonNull String name, @NonNull String info) {
  if (name.equals("color")) {
    switch (info) {
      case "green":
        // Set background color to green.
        break;
      case "blue":
        // Set background color to blue.
        break;
      default:
        // Set background color to black.
        break;
    }
  }
}

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.dispatchAppEvent("color", "green");

      document.getElementById("ad").addEventListener("click", function() {
        // Send a color=blue event when ad is clicked.
        admob.events.dispatchAppEvent("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>

請參考 Ad Manager 應用程式事件範例,瞭解如何在 API 試用版應用程式中導入應用程式事件。

Java Kotlin JetpackCompose

後續步驟

可收合橫幅

「可收合橫幅廣告」一開始顯示時,會以較大尺寸重疊在畫面上,當使用者點按收合按鈕,廣告就會恢復為較小尺寸。建議使用這種橫幅廣告來進一步提升成效,詳情請參閱「可收合橫幅廣告」。

自動調整內嵌橫幅廣告

與錨定式自動調整橫幅廣告相比,內嵌自動調整橫幅廣告的版面更大、更高,且高度可變,甚至可與裝置螢幕同高。如果應用程式會在可捲動內容中放送橫幅廣告,內嵌自動調整橫幅廣告會是比錨定式更好的選擇。詳情請參閱「內嵌自動調整橫幅廣告」。

探索其他主題