Instructivo: Prueba la adopción de nuevos formatos de anuncio de AdMob

Paso 3: Controla los valores de los parámetros Remote Config en el código de tu app


Introducción: Prueba la adopción de nuevos formatos de anuncios de AdMob con Firebase
Paso 1: Usa AdMob para crear una nueva variante de unidad de anuncios para pruebas
Paso 2: Configura una prueba A/B en la consola de Firebase

Paso 3: Controla los valores de los parámetros Remote Config en el código de tu app

Paso 4: Comienza la prueba A/B y revisa los resultados en la consola de Firebase
Paso 5: Decide si vas a lanzar el nuevo formato de anuncio


Al final del paso anterior, creaste un parámetro Remote Config (SHOW_NEW_AD_KEY). En este paso, agregarás al código de tu app la lógica que determina lo que debe mostrar según el valor de ese parámetro: true (mostrar el anuncio nuevo) o false (no mostrar el anuncio nuevo).

Agrega los SDK requeridos

Antes de usar Remote Config en el código de la aplicación, agrega el SDK de Remote Config y el SDK de Firebase para Google Analytics a los archivos de compilación de tu proyecto.

Plataformas de Apple

Agrega y, luego, instala los siguientes pods en tu Podfile:

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

Android

Agrega las siguientes dependencias de biblioteca a tu archivo build.gradle:

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

Unity

Descarga y, luego, instala el SDK de Firebase Unity y agrega los siguientes paquetes de Unity a tu proyecto:

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

Configura la instancia de Remote Config

Para usar los valores de parámetros de Remote Config, configura la instancia de Remote Config para que esté configurada para recuperar valores nuevos de la instancia de app del cliente.

En este ejemplo, Remote Config se configura para verificar si hay valores de parámetros nuevos una 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");
}

Cómo recuperar y activar Remote Config

Recupera y activa los parámetros Remote Config para que pueda comenzar a usar los valores de parámetros nuevos.

Es recomendable que realices la llamada lo antes posible en la fase de carga de tu app, ya que la llamada es asíncrona y necesitarás el valor de Remote Config recuperado previamente para que tu app sepa si debe mostrar el anuncio.

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

Tu app ya está lista para controlar el parámetro Remote Config que creaste durante la prueba A/B que se configuró en un paso anterior del instructivo.

Usa el valor del parámetro Remote Config

Usa el valor Remote Config recuperado previamente en la función loadAdUnit() para determinar si la instancia de la app debe mostrar (valor del parámetro true) o no mostrar (valor del parámetro false) la nueva unidad de anuncios intersticiales recompensados.

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

Agrega otras verificaciones para el valor del parámetro

Existen otras áreas en el código de la aplicación en las que deberás verificar el valor de este parámetro Remote Config para determinar qué experiencia del anuncio se cargará. Por ejemplo, puedes decidir si se debe volver a cargar un anuncio después de que el usuario termine de ver el actual.

Las llamadas de recuperación y activación deben realizarse primero para obtener cualquier cambio en el valor del parámetro, por ejemplo, si decides finalizar o crear un experimento nuevo.

A partir de ahí, siempre puedes verificar el valor del parámetro mediante las siguientes llamadas:

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

Estas llamadas siempre mostrarán el mismo valor para una instancia de app según si se ubicaron en el grupo de control o en el grupo nuevo de variantes de anuncios, a menos que se hayan realizado cambios en la consola de Firebase que se recuperaron y activaron en las llamadas anteriores.




Paso 2: Configura una prueba A/B en la consola de Firebase Paso 4: Inicia la prueba A/B y revisa los resultados