设置插页式激励广告

新一代 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 提供多个定位配置,请传递自定义字符串标识符。

获取并展示预加载的广告

当您想展示广告时,请调用 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 查询参数。如果未设置自定义数据值,custom_data 查询参数值不会出现在 SSV 回调中。

以下代码示例展示了如何在展示广告之前对插页式激励广告对象设置自定义数据:

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());