設定插頁式獎勵廣告

Next-Gen SDK。

插頁式獎勵廣告格式會在應用程式自然轉換時自動顯示廣告,並向使用者發放獎勵。與獎勵廣告不同的是,插頁式獎勵廣告不需等使用者選擇觀看即可放送。詳情請參閱插頁式獎勵廣告指南

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

事前準備

繼續操作前,請先執行下列工作:

  • 設定 GMA Next-Gen SDK
  • 使用測試插頁式獎勵廣告單元 ID ca-app-pub-3940256099942544/5354046379
    • 建構及測試應用程式時,請務必使用測試廣告,而非實際的正式廣告,否則可能導致帳戶遭停權。
    • 發布應用程式前,請將這個 ID 換成您的廣告單元 ID。
    • 如要進一步瞭解 GMA Next-Gen SDK 測試廣告,請參閱「啟用測試廣告」。

瞭解廣告預先載入

GMA Next-Gen SDK 中的廣告預先載入功能會自動載入及快取廣告。

預先載入廣告有以下好處:

  • 參照管理:維護參照,直到廣告顯示為止。
  • 自動重新載入:從快取擷取廣告時,載入新廣告。
  • 管理重試:如果廣告無法載入,系統會載入新廣告。
  • 到期處理:在廣告到期前重新整理廣告。
  • 快取最佳化:最佳化快取順序,放送最高優先順序的廣告。

開始預先載入廣告

如要開始預先載入廣告,請在應用程式啟動時呼叫一次 startPreload() 方法。呼叫 startPreload() 方法後,GMA Next-Gen SDK 會自動預先載入廣告,並重試預先載入設定的失敗要求。

以下範例說明如何開始預先載入廣告:

Kotlin

// Call start() once after SDK initialization.
// Preload only one ad unit per format to optimize performance.
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)

Java

// Call start() once after SDK initialization.
// Preload only one ad unit per format to optimize performance.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);

AD_UNIT_ID 替換為廣告單元 ID。

上一個範例說明如何使用廣告單元 ID 做為預先載入 ID。預先載入 ID 是您建立的字串 ID,用於識別廣告預先載入設定。如果應用程式需要為同一個廣告單元 ID 設定多個指定目標,請傳遞自訂字串 ID。

取得並顯示預先載入的廣告

如要顯示廣告,請呼叫 pollAd() 方法。GMA Next-Gen SDK 會擷取可用的廣告,並在背景自動預先載入下一個廣告。如果沒有可用廣告,GMA Next-Gen SDK 就不會傳回任何廣告。

取得可用的廣告物件後,請呼叫 show 方法來顯示廣告。使用獎勵事件監聽器處理獎勵事件。以下範例說明如何擷取及顯示預先載入的廣告:

Kotlin

private fun pollAndShowAd(activity: Activity, adUnitId: String) {
  // Polling returns the next available ad and loads another ad in the background.
  val ad = RewardedInterstitialAdPreloader.pollAd(adUnitId)
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.")
    return
  }

  // Interact with the ad object as needed.
  Log.d(TAG, "Rewarded interstitial ad response info: ${ad.getResponseInfo()}")
  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdImpression() {
        Log.d(TAG, "Rewarded interstitial ad recorded an impression.")
      }
    }
  ad.show(activity) { rewardItem -> Log.d(TAG, "User earned reward: ${rewardItem.amount}") }
}

Java

private void pollAndShowAd(Activity activity, String adUnitId) {
  // Polling returns the next available ad and loads another ad in the background.
  final RewardedInterstitialAd ad = RewardedInterstitialAdPreloader.pollAd(adUnitId);

  // Interact with the ad object as needed.
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.");
    return;
  }

  Log.d(TAG, "Rewarded interstitial ad response info: " + ad.getResponseInfo());
  ad.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdImpression() {
          Log.d(TAG, "Rewarded interstitial ad recorded an impression.");
        }
      });

  // Show the ad.
  ad.show(
      activity,
      rewardItem -> {
        Log.d(TAG, "User earned reward: " + rewardItem.getAmount());
      });
}

請在準備好顯示廣告之後,再呼叫 pollAd() 方法。如要讀取廣告回應資訊但不顯示,請參閱「讀取回應資訊」。

監聽廣告事件

顯示廣告前,請先監聽廣告事件。以下範例說明如何註冊廣告事件的回呼:

Kotlin

private fun listenToAdEvents() {
  // Listen for ad events.
  val ad = rewardedInterstitialAd
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.")
    return
  }

  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdShowedFullScreenContent() {
        // Rewarded interstitial ad did show.
      }

      override fun onAdDismissedFullScreenContent() {
        // Rewarded interstitial ad did dismiss.
        rewardedInterstitialAd = null
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError
      ) {
        // Rewarded interstitial ad failed to show.
        Log.e(TAG, "Rewarded interstitial ad failed to show: ${fullScreenContentError.message}")
      }

      override fun onAdImpression() {
        // Rewarded interstitial ad did record an impression.
      }

      override fun onAdClicked() {
        // Rewarded interstitial ad did record a click.
      }
    }
}

Java

private void listenToAdEvents() {
  // Listen for ad events.
  if (rewardedInterstitialAd == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.");
    return;
  }

  rewardedInterstitialAd.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdShowedFullScreenContent() {
          // Rewarded interstitial ad did show.
        }

        @Override
        public void onAdDismissedFullScreenContent() {
          // Rewarded interstitial ad did dismiss.
          rewardedInterstitialAd = null;
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          // Rewarded interstitial ad failed to show.
          Log.e(
              TAG,
              "Rewarded interstitial ad failed to show: " + fullScreenContentError.getMessage());
        }

        @Override
        public void onAdImpression() {
          // Rewarded interstitial ad did record an impression.
        }

        @Override
        public void onAdClicked() {
          // Rewarded interstitial ad did record a click.
        }
      });
}

選用:驗證伺服器端驗證 (SSV) 回呼

如果應用程式需要在伺服器端驗證回呼中加入額外資料,請使用插頁式獎勵廣告的自訂資料功能。在插頁式獎勵廣告物件上設定的任何字串值,都會傳遞至 SSV 回呼的 custom_data 查詢參數。如未設定任何自訂資料值,SSV 回呼就不會包含 custom_data 查詢參數值。

請參考以下程式碼範例,瞭解如何在顯示廣告前,於插頁式獎勵廣告物件上設定自訂資料:

Kotlin

RewardedInterstitialAd.load(
  context,
  AD_UNIT_ID,
  AdRequest.Builder().build(),
  object : RewardedInterstitialAdLoadCallback() {
    override fun onAdLoaded(ad: RewardedInterstitialAd) {
      rewardedInterstitialAd = ad
      val options =
        ServerSideVerificationOptions.Builder().setCustomData("SAMPLE_CUSTOM_DATA_STRING").build()
      rewardedInterstitialAd?.setServerSideVerificationOptions(options)
    }
  },
)

Java

RewardedInterstitialAd.load(
    context,
    AD_UNIT_ID,
    new AdRequest.Builder().build(),
    new RewardedInterstitialAdLoadCallback() {
      @Override
      public void onAdLoaded(RewardedInterstitialAd ad) {
        rewardedInterstitialAd = ad;
        ServerSideVerificationOptions options =
            new ServerSideVerificationOptions.Builder()
                .setCustomData("SAMPLE_CUSTOM_DATA_STRING")
                .build();
        rewardedInterstitialAd.setServerSideVerificationOptions(options);
      }
    });

SAMPLE_CUSTOM_DATA_STRING 替換成自訂資料。

選用:監聽預先載入事件

開始預先載入廣告時,請註冊預先載入事件,以便在廣告預先載入成功、預先載入失敗或廣告快取空間不足時收到通知。

以下範例說明如何註冊預先載入廣告事件:

Kotlin

val preloadCallback =
  // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
  object : PreloadCallback {
    override fun onAdFailedToPreload(preloadId: String, adError: LoadAdError) {
      Log.d(
        TAG,
        "Rewarded interstitial preload ad $preloadId failed to load with error: ${adError.message}",
      )
    }

    override fun onAdsExhausted(preloadId: String) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is not available")
      // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
    }

    override fun onAdPreloaded(preloadId: String, responseInfo: ResponseInfo) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is available")
    }
  }
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback)

Java

PreloadCallback preloadCallback =
    // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
    new PreloadCallback() {
      @Override
      public void onAdFailedToPreload(@NonNull String preloadId, @NonNull LoadAdError adError) {
        Log.d(
            TAG,
            String.format(
                "Rewarded interstitial preload ad %s failed to load with error: %s",
                preloadId, adError.getMessage()));
        // [Optional] Get the error response info for additional details.
        // ResponseInfo responseInfo = adError.getResponseInfo();
      }

      @Override
      public void onAdsExhausted(@NonNull String preloadId) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is not available");
        // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
      }

      @Override
      public void onAdPreloaded(@NonNull String preloadId, @NonNull ResponseInfo responseInfo) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is available");
      }
    };
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback);

如果廣告無法載入,GMA Next-Gen SDK 會自動預先載入廣告,並重試預先載入設定的失敗要求。

選用:檢查廣告是否可用

如要瞭解廣告是否可用,請檢查廣告可用性。以下範例說明如何檢查預先載入的廣告是否可用:

Kotlin

private fun isAdAvailable(adUnitId: String): Boolean {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId)
}

Java

private boolean isAdAvailable(String adUnitId) {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId);
}

選用:設定緩衝區空間

緩衝區空間會控管記憶體中預先載入的廣告數量。根據預設,Google 會調整緩衝區大小,以平衡記憶體用量和廣告放送延遲。您可以設定自訂緩衝區空間,增加記憶體中保留的廣告數量。建議緩衝區空間上限為 4。

以下範例說明如何將預先載入的廣告緩衝區空間設為 4:

Kotlin

val adRequest = AdRequest.Builder(adUnitId).build()
// Maintain small or default buffer size unless rapid transitions are expected.
val preloadConfig = PreloadConfiguration(adRequest, bufferSize = 4)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)

Java

// Maintain small or default buffer size unless rapid transitions are expected.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest, 4);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);

預先載入快取限制

GMA Next-Gen SDK 會對所有廣告單元和預先載入 ID 的預先載入廣告總數,強制執行應用程式範圍的限制:

  • 預設限制:Google 最多會在記憶體中保留 6 個預先載入的廣告。這項限制適用於所有格式和預先載入 ID。
  • 建議每個預先載入 ID 的緩衝區空間為 2 或 3。

選用:停止預先載入廣告

如果不需要在工作階段中再次顯示特定預先載入 ID 的廣告,可以停止預先載入廣告。如要停止載入特定預先載入 ID 的廣告,請使用預先載入 ID 呼叫 destroy() 方法。呼叫 destroy() 方法會從快取中移除與預先載入 ID 相關聯的所有預先載入廣告。

以下範例說明如何停止預先載入廣告:

Kotlin

private fun stopPreloading(adUnitId: String) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId)
}

Java

private void stopPreloading(String adUnitId) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId);
}

選用:閱讀回覆資訊

讀取下一個預先載入的廣告回應資訊,但不會從快取中移除廣告。

以下範例說明如何讀取下一個預先載入的廣告回應資訊:

Kotlin

val responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId)
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.")
  return
}

Log.d(TAG, "Peeked ad response ID: ${responseInfo.responseId}")

Java

ResponseInfo responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId);
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.");
  return;
}

Log.d(TAG, "Peeked ad response ID: " + responseInfo.getResponseId());