Paso 3: Maneje los valores de los parámetros de configuración remota en el código de su aplicación
Introducción: probar la adopción del nuevo formato de anuncio de AdMob con Firebase |
Paso 1: Use AdMob para crear una nueva variante de bloque de anuncios para probar |
Paso 2: configura una prueba A/B en Firebase console |
Paso 3: Maneje los valores de los parámetros de configuración remota en el código de su aplicación |
Paso 4: Inicie la prueba A/B y revise los resultados de la prueba en la consola de Firebase |
Paso 5: Decida si implementará el nuevo formato de anuncio |
Al final del último paso, creó un parámetro de configuración remota ( SHOW_NEW_AD_KEY
). En este paso, agregará la lógica al código de su aplicación para lo que su aplicación debe mostrar en función del valor de ese parámetro: true
(mostrar el nuevo anuncio) frente a false
( no mostrar el nuevo anuncio).
Agregue los SDK requeridos
Antes de usar Remote Config en el código de su aplicación, agregue el SDK de Remote Config y el SDK de Firebase para Google Analytics a los archivos de compilación de su proyecto.
Rápido
Agregue e instale los siguientes pods en su podfile:
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
C objetivo
Agregue e instale los siguientes pods en su podfile:
pod 'Google-Mobile-Ads-SDK'
pod 'Firebase/Analytics'
pod 'Firebase/RemoteConfig'
Java
Agregue las siguientes dependencias de biblioteca a su archivo build.gradle
:
implementation 'com.google.android.gms:play-services-ads:21.5.0'
implementation 'com.google.firebase:firebase-analytics:21.2.0'
implementation 'com.google.firebase:firebase-config:21.2.1'
Kotlin+KTX
Agregue las siguientes dependencias de biblioteca a su archivo build.gradle
:
implementation 'com.google.android.gms:play-services-ads:21.5.0'
implementation 'com.google.firebase:firebase-analytics-ktx:21.2.0'
implementation 'com.google.firebase:firebase-config-ktx:21.2.1'
Unidad
Descarga e instala el SDK de Firebase Unity, luego agrega los siguientes paquetes de Unity a tu proyecto:
-
FirebaseAnalytics.unitypackage
-
FirebaseRemoteConfig.unitypackage
Configurar la instancia de Remote Config
Para usar los valores de los parámetros de Remote Config, configure la instancia de Remote Config para que esté configurada para obtener nuevos valores para la instancia de la aplicación cliente.
En este ejemplo, Remote Config está configurado para buscar nuevos valores de parámetros una vez cada hora.
Rápido
remoteConfig = RemoteConfig.remoteConfig()
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 3600
remoteConfig.configSettings = settings
C objetivo
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+KTX
remoteConfig = Firebase.remoteConfig
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = 3600
}
remoteConfig.setConfigSettingsAsync(configSettings)
Unidad
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");
}
Obtener y activar Remote Config
Obtenga y active los parámetros de Remote Config para que pueda comenzar a usar los nuevos valores de parámetros.
Querrá realizar esta llamada lo antes posible en la fase de carga de su aplicación porque esta llamada es asíncrona y necesitará el valor de configuración remota precargado para que su aplicación sepa si mostrar el anuncio.
Rápido
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()
}
C objetivo
[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+KTX
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()
}
Unidad
remoteConfig.FetchAndActivateAsync().ContinueWithOnMainThread(task => {
if (task.IsFaulted) {
Debug.LogWarning("Config params failed to update");
} else {
Debug.Log("Config params updated: " + task.Result);
}
LoadAdUnit();
});
Su aplicación ahora está lista para manejar el parámetro de configuración remota que creó durante la prueba A/B configurada anteriormente en este tutorial.
Usar el valor del parámetro de configuración remota
Utilice el valor de Remote Config precargado en la función loadAdUnit()
para determinar si la instancia de la aplicación debe mostrar (valor de parámetro true
) o no mostrar (valor de parámetro false
) el nuevo bloque de anuncios intersticiales bonificados.
Rápido
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.
}
}
C objetivo
- (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+KTX
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.
}
}
Unidad
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.
}
}
Agregar otras comprobaciones para el valor del parámetro
Hay otras áreas en el código de su aplicación donde deberá verificar el valor de este parámetro de configuración remota para dictar qué experiencia publicitaria se cargará. Por ejemplo, puede decidir si recargar un anuncio después de que el usuario haya terminado de ver el actual.
Las llamadas de obtención y activación deben realizarse primero para obtener cualquier cambio en el valor de los parámetros, por ejemplo, si decide finalizar o crear un nuevo experimento.
Desde allí, siempre puede verificar el valor del parámetro usando las siguientes llamadas:
Rápido
remoteConfig["showNewAdKey"].boolValue
C objetivo
self.remoteConfig[@"SHOW_NEW_AD_KEY"].boolValue;
Java
mFirebaseRemoteConfig.getBoolean(SHOW_NEW_AD_KEY)
Kotlin+KTX
remoteConfig.getBoolean(SHOW_NEW_AD_KEY)
Unidad
remoteConfig.GetValue("SHOW_NEW_AD_KEY").BooleanValue
Estas llamadas siempre devolverán el mismo valor para una instancia de la aplicación, dependiendo de si se colocó en el grupo de control o en el nuevo grupo 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 : Configure una prueba A/B en Firebase consolePaso 4 : Inicie la prueba A/B y revise los resultados de la prueba