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

Etapa 3: lidar com os valores dos parâmetros do Configuração remota no código do seu app



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

Adicione os SDKs necessários

Antes de usar a Configuração remota no código do seu aplicativo, adicione o SDK da Configuração remota e o SDK do Firebase para Google Analytics aos arquivos de criação do projeto.

Adicione e instale os seguintes pods em seu podfile:

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

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

implementation 'com.google.android.gms:play-services-ads:23.0.0'
implementation
'com.google.firebase:firebase-analytics:21.6.1'
implementation
'com.google.firebase:firebase-config:21.6.3'

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

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

Configurar instância do Configuração remota

Para usar os valores dos parâmetros do Configuração remota, configure a instância do Configuração remota para que ela seja configurada para buscar novos valores para a instância do aplicativo cliente.

Neste exemplo, o Configuração remota está configurado para verificar novos valores de parâmetros uma vez a cada hora.

remoteConfig = RemoteConfig.remoteConfig()
let settings
= RemoteConfigSettings()
settings
.minimumFetchInterval = 3600
remoteConfig
.configSettings = settings
self.remoteConfig = [FIRRemoteConfig remoteConfig];
FIRRemoteConfigSettings *remoteConfigSettings = [[FIRRemoteConfigSettings alloc] init];
remoteConfigSettings
.minimumFetchInterval = 3600;
self.remoteConfig.configSettings = remoteConfigSettings;
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
       
.setMinimumFetchIntervalInSeconds(3600)
       
.build();
mFirebaseRemoteConfig
.setConfigSettingsAsync(configSettings);
remoteConfig = Firebase.remoteConfig
val configSettings
= remoteConfigSettings {
    minimumFetchIntervalInSeconds
= 3600
}
remoteConfig
.setConfigSettingsAsync(configSettings)
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 a Configuração remota

Busque e ative os parâmetros do Configuração remota para que ele possa começar a usar os novos valores dos parâmetros.

Você desejará fazer essa chamada o mais cedo possível na fase de carregamento do seu aplicativo, porque essa chamada é assíncrona e você precisará do valor da Configuração remota pré-buscado para que seu aplicativo saiba se deve exibir o anúncio.

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()
}
[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];
}];
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
();
           
}
       
});
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
()
       
}
remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task => {
 
if (task.IsFaulted) {
   
Debug.LogWarning("Config params failed to update");
 
} else {
   
Debug.Log("Config params updated: " + task.Result);
 
}
 
LoadAdUnit();
});

Seu aplicativo agora está pronto para lidar com o parâmetro do Configuração remota que você criou durante o teste A/B configurado anteriormente neste tutorial.

Usar o valor do parâmetro Configuração remota

Use o valor pré-buscado da Configuração remota na função loadAdUnit() para determinar se a instância do aplicativo deve mostrar (valor do parâmetro true ) ou não (valor do parâmetro false ) o novo bloco de anúncios intersticiais premiados.

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.
 
}
}
- (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.
   
}
}
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.
   
}
}
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.
   
}
}
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.
 
}
}

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

Há outras áreas no código do seu aplicativo onde você precisará verificar o valor desse parâmetro da Configuração remota para determinar qual experiência de anúncio será carregada. Por exemplo, você pode decidir se deseja recarregar um anúncio depois que o usuário terminar de visualizar o atual.

As chamadas fetch e activate devem ser feitas primeiro para obter quaisquer alterações no valor do parâmetro — por exemplo, se você decidir encerrar ou criar um novo experimento.

A partir daí, você sempre pode verificar o valor do parâmetro usando as seguintes chamadas:

remoteConfig["showNewAdKey"].boolValue
self.remoteConfig[@"SHOW_NEW_AD_KEY"].boolValue;
mFirebaseRemoteConfig.getBoolean(SHOW_NEW_AD_KEY)
remoteConfig.getBoolean(SHOW_NEW_AD_KEY)
remoteConfig.GetValue("SHOW_NEW_AD_KEY").BooleanValue

Essas chamadas sempre retornarão o mesmo valor para uma instância de aplicativo, dependendo se ela foi colocada no grupo de controle ou no novo grupo de variantes de anúncio, a menos que tenham sido feitas alterações no Firebase console que foram buscadas e ativadas nas chamadas anteriores.




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