Catch up on highlights from Firebase at Google I/O 2023. Learn more

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

Passaggio 3: gestisci i valori dei parametri di configurazione remota nel codice dell'app


Introduzione: prova l'adozione del nuovo formato degli 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 di configurazione remota nel codice dell'app

Passaggio 4: avvia il test A/B e rivedi 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 la tua app dovrebbe visualizzare in base al valore di quel 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 progetto.

Veloce

Aggiungi e installa i seguenti pod nel tuo podfile:

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

Obiettivo-C

Aggiungi e installa i seguenti pod nel tuo podfile:

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

Java

Aggiungi le seguenti dipendenze della libreria al tuo file build.gradle :

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

Kotlin+KTX

Aggiungi le seguenti dipendenze della libreria al tuo file build.gradle :

implementation 'com.google.android.gms:play-services-ads:22.1.0'
implementation 'com.google.firebase:firebase-analytics-ktx:21.3.0'
implementation 'com.google.firebase:firebase-config-ktx:21.4.0'

Unità

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

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

Configura l'istanza di configurazione remota

Per usare i valori del parametro Remote Config, configurare l'istanza di Remote Config in modo che sia configurata per recuperare nuovi valori per l'istanza dell'app client.

In questo esempio, Remote Config è configurato per controllare i 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 Configurazione remota

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

Ti consigliamo di effettuare questa chiamata il prima possibile durante la fase di caricamento della tua app perché questa chiamata è asincrona e avrai bisogno del valore Remote Config precaricato 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 Configurazione remota

Utilizza il valore di configurazione remota precaricato nella funzione loadAdUnit() per determinare se l'istanza dell'app deve mostrare (valore del parametro true ) o meno (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

Ci sono altre aree nel codice dell'applicazione in cui dovrai controllare 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 terminato di visualizzare quello corrente.

Le chiamate di recupero e attivazione devono essere effettuate prima per ottenere eventuali modifiche al valore dei parametri, ad esempio se si decide di terminare o creare un nuovo esperimento.

Da lì, puoi sempre controllare il valore per il 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 di annunci, a meno che non siano state apportate modifiche nella console Firebase che sono state recuperate e attivate nelle chiamate precedenti.




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