插頁式廣告

選取平台: Android iOS Unity Flutter

插頁式廣告會全螢幕顯示,覆蓋整個應用程式的介面。 這類廣告通常顯示在應用程式流程中的自然轉換點, 例如操作後的空檔或遊戲關卡之間的暫停時間。應用程式顯示插頁式廣告時,使用者可選擇輕觸廣告前往到達網頁,或是關閉廣告返回應用程式。

本指南說明如何在 Flutter 應用程式中整合中繼插頁廣告。

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

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

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

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

測試廣告單元經過設定,可針對每項要求傳回測試廣告。您編寫程式碼、測試及偵錯時,可以在自己的應用程式中自由使用。但請務必留意,在發布應用程式前,將這些 ID 換成您自己的廣告單元 ID。

載入廣告

以下範例會載入插頁式廣告:

InterstitialAd.load(
  adUnitId: "_adUnitId",
  request: const AdRequest(),
  adLoadCallback: InterstitialAdLoadCallback(
    onAdLoaded: (InterstitialAd ad) {
      // Called when an ad is successfully received.
      debugPrint('Ad was loaded.');
      // Keep a reference to the ad so you can show it later.
      _interstitialAd = ad;
    },
    onAdFailedToLoad: (LoadAdError error) {
      // Called when an ad request failed.
      debugPrint('Ad failed to load with error: $error');
    },
  ),
);

_adUnitId 替換為您自己的廣告單元 ID。

插頁式廣告事件

您可以使用 FullScreenContentCallback 監聽生命週期事件,例如廣告顯示或關閉時。顯示廣告前,請先設定 InterstitialAd.fullScreenContentCallback,以便接收這些事件的通知。這個範例會實作每個方法:

ad.fullScreenContentCallback = FullScreenContentCallback(
  onAdShowedFullScreenContent: (ad) {
    // Called when the ad showed the full screen content.
    debugPrint('Ad showed full screen content.');
  },
  onAdFailedToShowFullScreenContent: (ad, err) {
    // Called when the ad failed to show full screen content.
    debugPrint('Ad failed to show full screen content with error: $err');
    // Dispose the ad here to free resources.
    ad.dispose();
  },
  onAdDismissedFullScreenContent: (ad) {
    // Called when the ad dismissed full screen content.
    debugPrint('Ad was dismissed.');
    // Dispose the ad here to free resources.
    ad.dispose();
  },
  onAdImpression: (ad) {
    // Called when an impression occurs on the ad.
    debugPrint('Ad recorded an impression.');
  },
  onAdClicked: (ad) {
    // Called when a click is recorded for an ad.
    debugPrint('Ad was clicked.');
  },
);

顯示插頁式廣告

InterstitialAd 會顯示為 Overlay,位於所有應用程式內容的頂端,且位置固定,因此無法新增至 Flutter 小工具樹狀結構。您可以呼叫 show(),選擇廣告顯示時間。

_interstitialAd?.show();

呼叫 show() 後,以這種方式顯示的 Ad 無法以程式輔助方式關閉,必須由使用者輸入內容。InterstitialAd 只能顯示一次。後續呼叫顯示畫面時,系統會觸發 onAdFailedToShowFullScreenContent

不再需要存取廣告時,必須將廣告物件捨棄。呼叫 dispose() 的最佳做法位於 FullScreenContentCallback.onAdDismissedFullScreenContentFullScreenContentCallback.onAdFailedToShowFullScreenContent 回呼中。

大功告成!您的應用程式現在可以顯示插頁式廣告。

後續步驟

GitHub 上的完整範例

插頁式廣告