Tutorial: testar a adoção de novos formatos de anúncio da AdMob

Etapa 3: lidar com os valores de parâmetros Remote Config no código do app


Introdução: testar a nova adoção de um formato de anúncio AdMob usando o Firebase
Etapa 1: usar AdMob para criar uma nova variante de bloco de anúncios para teste
Etapa 2: configurar um teste A/B no console do Firebase

Etapa 3: lidar com os valores de parâmetros Remote Config no código do app

Etapa 4: iniciar o teste A/B e analisar os resultados no console Firebase
Etapa 5: decidir se vai lançar o novo formato do anúncio


No final da última etapa, você criou um parâmetro Remote Config (SHOW_NEW_AD_KEY). Nesta etapa, vamos adicionar a lógica ao código do seu app para o que ele vai exibir com base no valor desse parâmetro: true (mostrar o novo anúncio) versus false (não mostrar o novo anúncio).

Adicionar os SDKs necessários

Antes de usar o Remote Config no código do seu aplicativo, adicione o SDK Remote Config e o SDK do Firebase para Google Analytics aos arquivos de build do projeto.

Plataformas da Apple

Adicione e instale os seguintes pods no seu podfile:

pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'

Android

Adicione as seguintes dependências de biblioteca ao seu arquivo build.gradle:

implementation 'com.google.android.gms:play-services-ads:24.2.0'
implementation 'com.google.firebase:firebase-analytics:22.4.0'
implementation 'com.google.firebase:firebase-config:22.1.0'

Unity

Faça o download do SDK do Firebase para Unity e o instale. Depois adicione os seguintes pacotes do Unity ao seu projeto:

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

Configurar a instância Remote Config

Para usar os valores de parâmetros Remote Config, configure a instância Remote Config para que ela seja usada para buscar novos valores para a instância do app cliente.

Neste exemplo, Remote Config está configurado para verificar novos valores de parâmetro uma vez por hora.

Swift

remoteConfig = RemoteConfig.remoteConfig()
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 3600
remoteConfig.configSettings = settings

Objective-C

self.remoteConfig = [FIRRemoteConfig remoteConfig];
FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] init];
remoteConfigSettings.minimumFetchInterval = 3600;
self.remoteConfig.configSettings = remoteConfigSettings;

Java

mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
        .setMinimumFetchIntervalInSeconds(3600)
        .build();
mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);

Kotlin

remoteConfig = Firebase.remoteConfig
val configSettings = remoteConfigSettings {
    minimumFetchIntervalInSeconds = 3600
}
remoteConfig.setConfigSettingsAsync(configSettings)

Unity

var remoteConfig = FirebaseRemoteConfig.DefaultInstance;
var configSettings = new ConfigSettings {
  MinimumFetchInternalInMilliseconds =
        (ulong)(new TimeSpan(1, 0, 0).TotalMilliseconds)
};
remoteConfig.SetConfigSettingsAsync(configSettings)
        .ContinueWithOnMainThread(task => {
          Debug.Log("Config settings confirmed");
}

Buscar e ativar Remote Config

Busque e ative os parâmetros Remote Config para que ele possa começar a usar os novos valores de parâmetros.

Faça essa chamada o quanto antes na fase de carregamento do app, porque ela é assíncrona e vai precisar do valor Remote Config pré-buscado para que o app saiba se vai exibir o anúncio.

Swift

remoteConfig.fetch() { (status, error) -> Void in
  if status == .success {
    print("Config fetched!")
    self.remoteConfig.activate() { (changed, error) in
      // ...
    }
  } else {
    print("Config not fetched")
    print("Error: \(error?.localizedDescription ?? "No error available.")")
  }
  self.loadAdUnit()
}

Objective-C

[self.remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError *error) {
    if (status == FIRRemoteConfigFetchStatusSuccess) {
        NSLog(@"Config fetched!");
      [self.remoteConfig activateWithCompletion:^(BOOL changed, NSError * _Nullable error) {
        // ...
      }];
    } else {
        NSLog(@"Config not fetched");
        NSLog(@"Error %@", error.localizedDescription);
    }
    [self loadAdUnit];
}];

Java

mFirebaseRemoteConfig.fetchAndActivate()
        .addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
            @Override
            public void onComplete(@NonNull Task<Boolean> task) {
                if (task.isSuccessful()) {
                    boolean updated = task.getResult();
                    Log.d(TAG, "Config params updated: " + updated);
                } else {
                    Log.d(TAG, "Config params failed to update");
                }
                loadAdUnit();
            }
        });

Kotlin

remoteConfig.fetchAndActivate()
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                val updated = task.result
                Log.d(TAG, "Config params updated: $updated")
            } else {
                Log.d(TAG, "Config params failed to update")
            }
            loadAdUnit()
        }

Unity

remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task => {
  if (task.IsFaulted) {
    Debug.LogWarning("Config params failed to update");
  } else {
    Debug.Log("Config params updated: " + task.Result);
  }
  LoadAdUnit();
});

Seu app agora está pronto para processar o parâmetro Remote Config que você criou durante o teste A/B configurado anteriormente neste tutorial.

Usar o valor do parâmetro Remote Config

Use o valor Remote Config pré-buscado na função loadAdUnit() para determinar se a instância do app precisa mostrar (valor do parâmetro de true) ou não mostrar (valor do parâmetro de false) o novo bloco de anúncios intersticiais premiado.

Swift

private func loadAdUnit() {
  let showNewAdFormat = remoteConfig["users"].boolValue
  if showNewAdFormat {
      // Load Rewarded Interstitial Ad.
      // This should load your new implemented ad unit
      // as per AdMob instructions (the first step of this tutorial).
  } else {
    // Show the existing ad unit.
  }
}

Objective-C

- (void)loadAdUnit {
    BOOL showAds = self.remoteConfig[@"SHOW_NEW_AD_KEY"].boolValue;
    if (showAds) {
      // Load Rewarded Interstitial Ad.
      // This should load your new implemented ad unit
      // per AdMob instructions (the first step of this tutorial).
    } else {
      // Show the existing ad unit.
    }
}

Java

private void loadAdUnit() {
    boolean showNewAdFormat =
      mFirebaseRemoteConfig.getBoolean(SHOW_NEW_AD_KEY);

    if (showNewAdFormat) {
      // Load Rewarded Interstitial Ad.
      // This should load your new implemented ad unit
      // per AdMob instructions (the first step of this tutorial).
    } else {
      // Show the existing ad unit.
    }
}

Kotlin

private fun loadAdUnit() {
  var showNewAdFormat = remoteConfig.getBoolean(SHOW_NEW_AD_KEY)

  if (showNewAdFormat) {
      // Load Rewarded Interstitial Ad.
      // This should load your new implemented ad unit
      // per AdMob instructions (the first step of this tutorial).
    } else {
      // Show the existing ad unit.
    }
}

Unity

void LoadAdUnit() {
  bool showNewAdFormat =
      remoteConfig.GetValue("SHOW_NEW_AD_KEY").BooleanValue;

  if (showNewAdFormat) {
    // Load Rewarded Interstitial Ad (new implemented ad unit)
    // per AdMob instructions (the first step of this tutorial).
  } else {
    // Show the existing ad unit.
  }
}

Adicionar outras verificações para o valor do parâmetro

Há outras áreas no código do aplicativo em que vai ser necessário verificar o valor do parâmetro Remote Config para determinar qual experiência do anúncio vai ser carregada. Por exemplo, é possível decidir se quer recarregar um anúncio depois que o usuário tiver terminado de visualizar o atual.

As chamadas de busca e ativação precisam ser feitas primeiro para que as alterações de valor dos parâmetros sejam recebidas, por exemplo, se você decidir encerrar ou criar um novo experimento.

Depois disso, você sempre vai poder verificar o valor do parâmetro usando as seguintes chamadas:

Swift

remoteConfig["showNewAdKey"].boolValue

Objective-C

self.remoteConfig[@"SHOW_NEW_AD_KEY"].boolValue;

Java

mFirebaseRemoteConfig.getBoolean(SHOW_NEW_AD_KEY)

Kotlin

remoteConfig.getBoolean(SHOW_NEW_AD_KEY)

Unity

remoteConfig.GetValue("SHOW_NEW_AD_KEY").BooleanValue

Essas chamadas sempre vão retornar o mesmo valor para uma instância de app, dependendo se ela tiver sido colocada no grupo de controle ou no novo grupo de variantes do anúncio, a menos que alguma mudança tenha sido feita no console Firebase que tenha sido buscada e ativada nas chamadas anteriores.




Etapa 2: configurar um teste A/B no console do Firebase Etapa 4: iniciar o teste A/B e analisar os resultados do teste