Tutorial: prova l'adozione dei nuovi formati di annunci AdMob

Passaggio 3: gestisci i valori dei parametri Remote Config nel codice della tua app


Introduzione: prova l'adozione del nuovo formato di annunci AdMob utilizzando Firebase
Passaggio 1: utilizza AdMob per creare una nuova variante di unità pubblicitaria da testare
Passaggio 2: imposta un test A/B nella console Firebase

Passaggio 3: gestisci i valori dei parametri Remote Config nel codice della tua app

Passaggio 4: avvia il test A/B ed esamina i risultati del test nella console Firebase
Passaggio 5: decidi se implementare il nuovo formato dell'annuncio


Alla fine dell'ultimo passaggio, hai creato un parametro Remote Config ( SHOW_NEW_AD_KEY ). In questo passaggio aggiungerai la logica al codice della tua app per ciò che l'app deve visualizzare in base al valore di tale parametro: true (mostra il nuovo annuncio) rispetto a false ( non mostra il nuovo annuncio).

Aggiungi gli SDK richiesti

Prima di utilizzare Remote Config nel codice dell'applicazione, aggiungi sia l'SDK Remote Config che l'SDK Firebase per Google Analytics ai file di build del tuo progetto.

Piattaforme Apple

Aggiungi e installa i seguenti pod nel tuo podfile:

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

Androide

Aggiungi le seguenti dipendenze della libreria al tuo file 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'

Unità

Scarica e installa Firebase Unity SDK, quindi aggiungi i seguenti pacchetti Unity al tuo progetto:

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

Configura l'istanza di Remote Config

Per utilizzare i valori dei parametri Remote Config, configura l'istanza Remote Config in modo che sia configurata per recuperare nuovi valori per l'istanza dell'app client.

In questo esempio, Remote Config è configurato per verificare la presenza di nuovi valori dei parametri una volta ogni ora.

Veloce

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

Obiettivo-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+KTX

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

Unità

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

Recupera e attiva Remote Config

Recupera e attiva i parametri di Remote Config in modo che possa iniziare a utilizzare i nuovi valori dei parametri.

Ti consigliamo di effettuare questa chiamata il prima possibile nella fase di caricamento della tua app perché questa chiamata è asincrona e avrai bisogno del valore Remote Config prerecaricato in modo che la tua app sappia se mostrare l'annuncio.

Veloce

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

Obiettivo-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+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()
        }

Unità

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

La tua app è ora pronta per gestire il parametro Remote Config che hai creato durante il test A/B configurato in precedenza in questo tutorial.

Utilizzare il valore del parametro Remote Config

Utilizza il valore Remote Config prerecuperato nella funzione loadAdUnit() per determinare se l'istanza dell'app deve mostrare (valore del parametro true ) o non mostrare (valore del parametro false ) la nuova unità pubblicitaria interstitial con premio.

Veloce

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

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

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

Aggiungi altri controlli per il valore del parametro

Esistono altre aree nel codice dell'applicazione in cui dovrai verificare il valore di questo parametro Remote Config per stabilire quale esperienza pubblicitaria verrà caricata. Ad esempio, puoi decidere se ricaricare un annuncio dopo che l'utente ha finito di visualizzare quello corrente.

Le chiamate di recupero e attivazione devono essere effettuate per prime per ottenere eventuali modifiche ai valori dei parametri, ad esempio se decidi di terminare o creare un nuovo esperimento.

Da lì, puoi sempre verificare il valore del parametro utilizzando le seguenti chiamate:

Veloce

remoteConfig["showNewAdKey"].boolValue

Obiettivo-C

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

Java

mFirebaseRemoteConfig.getBoolean(SHOW_NEW_AD_KEY)

Kotlin+KTX

remoteConfig.getBoolean(SHOW_NEW_AD_KEY)

Unità

remoteConfig.GetValue("SHOW_NEW_AD_KEY").BooleanValue

Queste chiamate restituiranno sempre lo stesso valore per un'istanza dell'app a seconda che sia stata inserita nel gruppo di controllo o nel nuovo gruppo di varianti dell'annuncio, a meno che non siano state apportate modifiche nella console Firebase recuperate e attivate nelle chiamate precedenti.




Passaggio 2 : imposta un test A/B nella console Firebase Passaggio 4 : avvia il test A/B ed esamina i risultati del test