Migrar para o pré-carregamento de anúncios

O pré-carregamento de anúncios automatiza o carregamento, o armazenamento em cache e o recarregamento de anúncios em GMA Next-Gen SDK. Se você usa o carregamento único, migre para o pré-carregamento de anúncios para ter um gerenciamento automatizado do ciclo de vida, novas tentativas gerenciadas e seleção otimizada de anúncios. Para detalhes conceituais sobre o pré-carregamento de anúncios, consulte Pré-carregamento de anúncios. O pré-carregamento de anúncios oferece suporte aos formatos de anúncio de abertura do app, intersticial, premiado e intersticial premiado.

Nesta página, mostramos como migrar uma implementação de anúncio de carregamento único para o pré-carregamento de anúncios. Este guia usa anúncios intersticiais como exemplo, mas você pode aplicar o mesmo processo aos formatos de anúncio com suporte.

Pré-requisitos

Antes de continuar, faça o seguinte:

Solicitar anúncios com pré-carregamento de anúncios

No carregamento único, você solicita um único anúncio para cada solicitação de anúncio. Com o pré-carregamento de anúncios, você inicia o pré-carregador uma vez com o ID e a configuração de pré-carregamento.

Os exemplos a seguir comparam solicitações de anúncios com carregamento único e pré-carregamento de anúncios:

Kotlin

Carregamento único:

// Request a single ad.
val adRequest = AdRequest.Builder(adUnitId).build()
InterstitialAd.load(adRequest, adLoadCallback)

Pré-carregamento de anúncios:

// Start the preloader once with a preload configuration.
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
InterstitialAdPreloader.start(adUnitId, preloadConfig)

Java

Carregamento único:

// Request a single ad.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
InterstitialAd.load(adRequest, adLoadCallback);

Pré-carregamento de anúncios:

// Start the preloader once with a preload configuration.
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
InterstitialAdPreloader.start(adUnitId, preloadConfig);

Mudar para callbacks de pré-carregamento

No carregamento único, você anexa um callback de carregamento a cada solicitação de anúncio individual. Com o pré-carregamento de anúncios, você registra um listener de callback para observar as atualizações do cache do pré-carregador. Esses callbacks notificam seu app quando os anúncios terminam o pré-carregamento, não são carregados ou esgotam o cache.

Os exemplos a seguir comparam como registrar callbacks de pré-carregamento para carregamento único e pré-carregamento de anúncios:

Kotlin

Carregamento único:

// Listen for single ad request load results.
val adLoadCallback =
  object : AdLoadCallback<InterstitialAd> {
    override fun onAdLoaded(ad: InterstitialAd) {
      // Ad loaded for a single request.
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {
      Log.d(TAG, "Ad failed to load: ${adError.message}")
    }
  }

InterstitialAd.load(adRequest, adLoadCallback)

Pré-carregamento de anúncios:

// Observe cache updates across multiple ads.
val preloadCallback =
  object : PreloadCallback {
    override fun onAdPreloaded(
      preloadId: String,
      responseInfo: ResponseInfo,
    ) {
      // Ad preloaded into the cache and is ready to show.
    }

    override fun onAdFailedToPreload(
      preloadId: String,
      adError: LoadAdError,
    ) {
      Log.d(TAG, "Ad failed to preload: ${adError.message}")
    }

    override fun onAdsExhausted(preloadId: String) {
      // All preloaded ads in the cache have been shown.
      Log.d(TAG, "Ads exhausted for: $preloadId")
    }
  }

InterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback)

Java

Carregamento único:

// Listen for single ad request load results.
AdLoadCallback<InterstitialAd> adLoadCallback =
    new AdLoadCallback<InterstitialAd>() {
      @Override
      public void onAdLoaded(@NonNull InterstitialAd ad) {
        // Ad loaded for a single request.
      }

      @Override
      public void onAdFailedToLoad(@NonNull LoadAdError adError) {
        Log.d(TAG, "Ad failed to load: " + adError.getMessage());
      }
    };

InterstitialAd.load(adRequest, adLoadCallback);

Pré-carregamento de anúncios:

// Observe cache updates across multiple ads.
PreloadCallback preloadCallback =
    new PreloadCallback() {
      @Override
      public void onAdPreloaded(
          @NonNull String preloadId, @NonNull ResponseInfo responseInfo) {
        // Ad preloaded into the cache and is ready to show.
      }

      @Override
      public void onAdFailedToPreload(
          @NonNull String preloadId, @NonNull LoadAdError adError) {
        Log.d(TAG, "Ad failed to preload: " + adError.getMessage());
      }

      @Override
      public void onAdsExhausted(@NonNull String preloadId) {
        // All preloaded ads in the cache have been shown.
        Log.d(TAG, "Ads exhausted for: " + preloadId);
      }
    };

InterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback);

O pré-carregador invoca métodos de callback quando GMA Next-Gen SDK carrega ou armazena um anúncio em cache ou quando o app mostra um anúncio.

Mostrar anúncios do cache

No carregamento único, você salva o anúncio carregado em uma variável e o mostra quando disponível. Com o pré-carregamento de anúncios, quando um anúncio está disponível para exibição, você o recupera diretamente do cache. Nas duas abordagens, anexe o listener de eventos ao anúncio antes de mostrá-lo.

Os exemplos a seguir comparam a exibição de um anúncio com pré-carregamento de anúncios e carregamento único:

Kotlin

Carregamento único:

// Retrieve the ad from a saved variable.
val interstitialAd = this.interstitialAd ?: return
// Display the ad.
interstitialAd.show(activity)

Pré-carregamento de anúncios:

// Retrieve the ad directly from the preloader cache.
val interstitialAd = InterstitialAdPreloader.pollAd(adUnitId) ?: return
// Display the ad.
interstitialAd.show(activity)

Java

Carregamento único:

// Retrieve the ad from a saved variable.
InterstitialAd interstitialAd = this.interstitialAd;
if (interstitialAd == null) {
  return;
}
// Display the ad.
interstitialAd.show(activity);

Pré-carregamento de anúncios:

// Retrieve the ad directly from the preloader cache.
InterstitialAd interstitialAd = InterstitialAdPreloader.pollAd(adUnitId);
if (interstitialAd == null) {
  return;
}
// Display the ad.
interstitialAd.show(activity);

Remover o armazenamento em cache e o recarregamento manuais

O pré-carregador carrega automaticamente um anúncio de substituição quando você recebe o anúncio. Ao contrário do carregamento único, não é necessário armazenar referências de anúncios manualmente nem escrever a lógica de recarregamento.

Remova os seguintes padrões do seu código:

  • Armazenamento em cache de variáveis de membro: exclua as variáveis de membro que armazenam objetos de anúncio.
  • Recarregamentos manuais: exclua as chamadas de carregamento depois que o usuário dispensar o anúncio ou não conseguir mostrá-lo.
  • Timers de nova tentativa personalizados: exclua os gerenciadores de novas tentativas, os loops de espera e os timers. GMA Next-Gen SDK tenta novamente as solicitações de pré-carregamento com falha automaticamente.

Comparar exemplos completos

Os exemplos a seguir comparam uma implementação completa de anúncios intersticiais antes e depois da migração para o pré-carregamento de anúncios:

Kotlin

Carregamento único:

// 1. Maintain a member variable to store the ad.
private var interstitialAd: InterstitialAd? = null

// 2. Load the ad and listen for load completion.
private fun loadAd() {
  val adRequest = AdRequest.Builder(adUnitId).build()
  InterstitialAd.load(
    adRequest,
    object : AdLoadCallback<InterstitialAd> {
      override fun onAdLoaded(ad: InterstitialAd) {
        interstitialAd = ad
      }

      override fun onAdFailedToLoad(adError: LoadAdError) {
        interstitialAd = null
      }
    },
  )
}

// 3. Show the saved ad.
private fun showAd(activity: Activity) {
  val interstitialAd = this.interstitialAd ?: return
  interstitialAd.adEventCallback =
    object : InterstitialAdEventCallback {
      override fun onAdDismissedFullScreenContent() {
        // Reload the ad after dismissal in single-load integrations.
        loadAd()
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError,
      ) {
        Log.d(TAG, "Ad failed to show: ${fullScreenContentError.message}")
      }
    }
  interstitialAd.show(activity)
}

Pré-carregamento de anúncios:

// 1. Start preloading with a callback to listen for loaded ads.
private fun startPreloading(adUnitId: String) {
  val preloadCallback =
    object : PreloadCallback {
      override fun onAdPreloaded(
        preloadId: String,
        responseInfo: ResponseInfo,
      ) {
        // Ad preloaded successfully.
      }

      override fun onAdFailedToPreload(
        preloadId: String,
        adError: LoadAdError,
      ) {
        Log.d(TAG, "Ad failed to preload: ${adError.message}")
      }
    }

  val adRequest = AdRequest.Builder(adUnitId).build()
  val preloadConfig = PreloadConfiguration(adRequest)
  InterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback)
}

// 2. Show the ad immediately after polling.
private fun showAd(activity: Activity, adUnitId: String) {
  val interstitialAd = InterstitialAdPreloader.pollAd(adUnitId) ?: return
  interstitialAd.adEventCallback =
    object : InterstitialAdEventCallback {
      override fun onAdDismissedFullScreenContent() {
        // Preloading automatically fetches a replacement ad.
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError,
      ) {
        Log.d(TAG, "Ad failed to show: ${fullScreenContentError.message}")
      }
    }
  interstitialAd.show(activity)
}

Java

Carregamento único:

// 1. Maintain a member variable to store the ad.
private InterstitialAd interstitialAd;

// 2. Load the ad and listen for load completion.
private void loadAd() {
  AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
  InterstitialAd.load(
      adRequest,
      new AdLoadCallback<InterstitialAd>() {
        @Override
        public void onAdLoaded(@NonNull InterstitialAd ad) {
          interstitialAd = ad;
        }

        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError adError) {
          interstitialAd = null;
        }
      });
}

// 3. Show the saved ad.
private void showAd(Activity activity) {
  if (interstitialAd == null) {
    return;
  }
  interstitialAd.setAdEventCallback(
      new InterstitialAdEventCallback() {
        @Override
        public void onAdDismissedFullScreenContent() {
          // Reload the ad after dismissal in single-load integrations.
          loadAd();
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          Log.d(
              TAG,
              "Ad failed to show: " + fullScreenContentError.getMessage());
        }
      });
  interstitialAd.show(activity);
}

Pré-carregamento de anúncios:

// 1. Start preloading with a callback to listen for loaded ads.
private void startPreloading(String adUnitId) {
  PreloadCallback preloadCallback =
      new PreloadCallback() {
        @Override
        public void onAdPreloaded(
            @NonNull String preloadId, @NonNull ResponseInfo responseInfo) {
          // Ad preloaded successfully.
        }

        @Override
        public void onAdFailedToPreload(
            @NonNull String preloadId, @NonNull LoadAdError adError) {
          Log.d(TAG, "Ad failed to preload: " + adError.getMessage());
        }
      };

  AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
  PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
  InterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback);
}

// 2. Show the ad immediately after polling.
private void showAd(Activity activity, String adUnitId) {
  InterstitialAd interstitialAd = InterstitialAdPreloader.pollAd(adUnitId);
  if (interstitialAd == null) {
    return;
  }
  interstitialAd.setAdEventCallback(
      new InterstitialAdEventCallback() {
        @Override
        public void onAdDismissedFullScreenContent() {
          // Preloading automatically fetches a replacement ad.
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          Log.d(
              TAG,
              "Ad failed to show: " + fullScreenContentError.getMessage());
        }
      });
  interstitialAd.show(activity);
}

Próximas etapas

Confira os recursos a seguir para configurar recursos de pré-carregamento, integrar formatos de anúncio e testar sua implementação: