插頁式廣告

選取平台: Android iOS Unity Flutter

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

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

請務必使用測試廣告進行測試

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

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

Android

ca-app-pub-3940256099942544/1033173712

iOS

ca-app-pub-3940256099942544/4411468910

測試廣告單元會在每次請求時傳回測試廣告。在編寫程式碼、測試及偵錯階段,您可以自由在應用程式中使用這些廣告單元,但發布前記得要換成自己的廣告單元 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 只能顯示一次,再次呼叫 show() 會觸發 onAdFailedToShowFullScreenContent

不再需要某則廣告時,請務必釋放相關資源。最佳做法是在 FullScreenContentCallback.onAdDismissedFullScreenContentFullScreenContentCallback.onAdFailedToShowFullScreenContent 回呼中呼叫 dispose()

大功告成!您的應用程式已能順利顯示插頁式廣告。

後續步驟

GitHub 上的完整範例

插頁式廣告