Configurar anúncios intersticiais premiados

Os anúncios intersticiais premiados são um formato que permite oferecer recompensas em anúncios que aparecem automaticamente durante transições naturais do app. Diferente dos anúncios premiados, os usuários não precisam ativar a visualização dos intersticiais premiados.

Neste guia, explicamos como integrar anúncios intersticiais premiados a um app Android.

Antes de começar

Antes de continuar, faça o seguinte:

  • Configurar GMA Next-Gen SDK.
  • Use o ID do bloco de anúncios intersticiais premiados de teste /21775744923/example/rewarded-interstitial.
    • Ao criar e testar seu app, use anúncios de teste em vez de anúncios de produção ativos. Se não, sua conta poderá ser suspensa.
    • Antes de publicar o app, substitua esse ID pelo ID do seu bloco de anúncios.
    • Para mais detalhes sobre os anúncios de teste GMA Next-Gen SDK, consulte Ativar anúncios de teste.

Entender o pré-carregamento de anúncios (Beta)

O pré-carregamento de anúncios (Beta) em GMA Next-Gen SDK automatiza o carregamento e o armazenamento em cache de anúncios.

O pré-carregamento de anúncios oferece os seguintes benefícios:

  • Gerenciamento de referências: mantém as referências até que os anúncios sejam mostrados.
  • Recarregamento automático: carrega um novo anúncio quando um é recuperado do cache.
  • Repetições gerenciadas: carrega um novo anúncio quando um falha ao carregar.
  • Processamento de expiração: atualiza os anúncios antes de expirar.
  • Otimização do cache: otimiza a ordem do cache para veicular o anúncio de maior prioridade.

Iniciar o pré-carregamento de anúncios

Para começar a pré-carregar anúncios, chame o método start uma vez na inicialização do app. Depois de chamar o método start, GMA Next-Gen SDK pré-carrega anúncios automaticamente e repete as solicitações com falha para configurações pré-carregadas.

O exemplo a seguir mostra como iniciar o pré-carregamento de anúncios:

Kotlin

private fun startPreloading(adUnitId: String) {
  // 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

private void startPreloading(String adUnitId) {
  // 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);
}

Substitua AD_UNIT_ID pelo ID do seu bloco de anúncios.

O exemplo anterior mostra como usar o ID do bloco de anúncios como ID de pré-carregamento. Um ID de pré-carregamento é um identificador de string que você cria para identificar uma configuração de pré-carregamento de anúncios. Se o app exigir várias configurações de segmentação para o mesmo ID de bloco de anúncios, transmita um identificador de string personalizado.

Receber e mostrar o anúncio pré-carregado

Quando quiser mostrar um anúncio, chame o método pollAd. GMA Next-Gen SDK recupera um anúncio disponível e pré-carrega automaticamente o próximo anúncio em segundo plano. Se nenhum anúncio estiver disponível, GMA Next-Gen SDK não retornará anúncios.

Quando você tiver um objeto de anúncio disponível, chame o método show para mostrar o anúncio. Use um listener de recompensa para processar eventos premiados. O exemplo a seguir mostra como recuperar e mostrar um anúncio pré-carregado:

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

Evite chamar o método pollAd até que você esteja pronto para mostrar um anúncio. Para ler as informações de resposta do anúncio sem mostrá-lo, consulte Ler as informações de resposta.

Detectar eventos de anúncios

Antes de mostrar o anúncio, detecte eventos de anúncios. O exemplo a seguir mostra como registrar callbacks para eventos de anúncios:

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.
        }
      });
}

Opcional: validar callbacks de verificação do lado do servidor (SSV)

Se o app exigir dados extras em callbacks de verificação do lado do servidor, use o recurso de dados personalizados dos anúncios intersticiais premiados. Qualquer valor de string definido em um objeto de anúncio intersticial premiado é transmitido ao parâmetro de consulta custom_data do callback de SSV. Se nenhum valor de dados personalizado for definido, o valor do parâmetro de consulta custom_data não estará presente no callback de SSV.

O exemplo de código a seguir mostra como definir dados personalizados em um objeto de anúncio intersticial premiado antes de mostrar o anúncio:

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

Substitua SAMPLE_CUSTOM_DATA_STRING pelos seus dados personalizados.

Opcional: detectar eventos de pré-carregamento

Ao iniciar o pré-carregamento de anúncios, registre-se para eventos de pré-carregamento para receber notificações quando os anúncios forem pré-carregados com sucesso, falharem ao pré-carregar ou o cache de anúncios estiver esgotado.

O exemplo a seguir mostra como se registrar para eventos de pré-carregamento de anúncios:

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

Quando um anúncio falha ao carregar, GMA Next-Gen SDK pré-carrega anúncios automaticamente e repete solicitações com falha para configurações pré-carregadas.

Opcional: verificar a disponibilidade de anúncios

Se você precisar saber se um anúncio está disponível, verifique a disponibilidade dele. O exemplo a seguir mostra como verificar se um anúncio pré-carregado está disponível:

Kotlin

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

Java

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

Opcional: definir o tamanho do buffer

O tamanho do buffer controla o número de anúncios pré-carregados mantidos na memória. Por padrão, o Google otimiza o tamanho do buffer para equilibrar o consumo de memória e a latência de veiculação de anúncios. Você pode definir um tamanho de buffer personalizado para aumentar o número de anúncios mantidos na memória.

O exemplo a seguir mostra como definir um tamanho de buffer de dois anúncios pré-carregados:

Kotlin

private fun setBufferSize(adUnitId: String) {
  val adRequest = AdRequest.Builder(adUnitId).build()
  // Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
  val preloadConfig = PreloadConfiguration(adRequest, bufferSize = 2)
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)
}

Java

private void setBufferSize(String adUnitId) {
  AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
  // Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
  PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest, 2);
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);
}

Limites de cache de pré-carregamento

GMA Next-Gen SDK aplica um limite em todo o app ao número total de anúncios pré-carregados em todos os blocos de anúncios e IDs de pré-carregamento:

  • Limite padrão: o Google mantém um máximo de seis anúncios pré-carregados na memória. Esse limite é compartilhado em todos os formatos e IDs de pré-carregamento.
  • Recomendamos manter um tamanho de buffer de dois para cada ID de pré-carregamento.

Opcional: interromper o pré-carregamento de anúncios

Se você não precisar mostrar anúncios para um ID de pré-carregamento específico novamente na sessão, poderá interromper o pré-carregamento de anúncios. Para interromper o carregamento de anúncios para um ID de pré-carregamento específico, chame o método destroy com um ID de pré-carregamento. Chamar o método destroy remove todos os anúncios pré-carregados associados ao ID de pré-carregamento do cache.

O exemplo a seguir mostra como interromper o pré-carregamento de anúncios:

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

Opcional: ler as informações de resposta

Leia as informações de resposta do próximo anúncio pré-carregado sem remover o anúncio do cache.

O exemplo a seguir mostra como ler as informações de resposta do próximo anúncio pré-carregado:

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