教學課程:最佳化 AdMob 廣告展示頻率

步驟 3:在應用程式的程式碼中處理 Remote Config 參數值


簡介: 最佳化 AdMob 使用 Firebase 的廣告展示頻率
步驟 1: 使用 AdMob建立 新的測試用廣告單元變化版本
步驟 2: 設定 在 Firebase 控制台中進行 A/B 版本測試

步驟 3: 處理應用程式程式碼中的 Remote Config 參數值

步驟 4: 開始 在 Firebase 控制台中進行 A/B 版本測試和查看測試結果
步驟 5: 決定 是否推出新的廣告格式


在最後一個步驟結束時,您建立了 Remote Config 參數 (INTERSTITIAL_AD_KEY).在這個步驟中,您要在應用程式的程式碼中加入邏輯 ,根據該參數的值決定應用程式應顯示的內容。

新增必要的 SDK

在應用程式程式碼中使用 Remote Config之前,請將 Remote Config SDK 和 Google Analytics 專用 Firebase SDK 以便 您的專案版本檔案

Swift

在 Podfile 中新增並安裝下列 Pod:

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

目標-C

在 Podfile 中新增並安裝下列 Pod:

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

Android

build.gradle 檔案中新增以下程式庫依附元件:

implementation 'com.google.android.gms:play-services-ads:23.3.0'
implementation 'com.google.firebase:firebase-analytics:22.0.2'
implementation 'com.google.firebase:firebase-config:22.0.0'

Unity

下載並安裝 Firebase Unity SDK,然後新增下列 Unity 至專案中:

  • FirebaseAnalytics.unitypackage
  • FirebaseRemoteConfig.unitypackage

設定 Remote Config 執行個體

如要使用 Remote Config 參數值,請設定 設定為 Remote Config 例項來擷取 用戶端應用程式執行個體。

在這個範例中,Remote Config 已設為檢查新參數 每小時的值

Swift

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

目標-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)

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

擷取並啟用 Remote Config

擷取並啟用 Remote Config 參數,即可開始使用 新的參數值

建議您盡早在應用程式的載入階段進行此呼叫 因為這是非同步呼叫,所以需要 Remote Config 值 以便應用程式知道要顯示哪些廣告。

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

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

Unity

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

您的應用程式現在可以處理您建立的 Remote Config 參數了 。

使用 Remote Config 參數值

loadAdUnit() 函式中使用預先擷取的 Remote Config 值,即可: 判斷要為此應用程式執行個體顯示哪個廣告展示頻率變化版本。

Swift

private func loadAdUnit() {
  let adUnitId = remoteConfig["INTERSTITIAL_AD_KEY"].stringValue;
  let request = GADRequest()
  GADInterstitialAd.load(withAdUnitID: adUnitId,
                               request: request,
                     completionHandler: { [self] ad, error in
                       if let error = error {
                         print("Failed to load: \(error.localizedDescription)")
                         return
                       }
                       interstitial = ad
                       // Register for callbacks.
                     }
  )
}

// Register for callbacks.

目標-C

- (void)loadAdUnit {
    NSString *adUnitId =
      self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;

  GADRequest *request = [GADRequest request];
  [GADInterstitialAd loadAdWithAdUnitId:adUnitId
                         request:request
                         completionHandler:^(GADInterstitialAd *ad,
                             NSError *error) {
    if (error) {
      NSLog(@"Failed to load interstitial ad with error: %@",
        [error localizedDescription]);
      return;
    }

    self.interstitial = ad;
  }];
}

Java

private void loadAdUnit() {
    String adUnitId =
      mFirebaseRemoteConfig.getString("INTERSTITIAL_AD_KEY");

    // Load Interstitial Ad (assume adUnitId not null)
    AdRequest adRequest = new AdRequest.Builder().build();

    InterstitialAd.load(this, adUnitId, adRequest, new
        InterstitialAdLoadCallback() {
          @Override
          public void onAdLoaded(@NonNull InterstitialAd intertitialAd) {
            mInterstitialAd = interstitialAd;
          }

          @Override
          public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
            mInterstitialAd = null;
          }
    });
}

Kotlin+KTX

private fun loadAdUnit() {
  String adUnitId = remoteConfig.getString("INTERSTITIAL_AD_KEY")
  var adRequest = AdRequestBuilder.Builder().build()

  AdRequestBuilder.load(this, adUnitId, adRequest, object :
    InterstitialAdLoadCallback() {
      override fun onAdFailedToLoad(adError: LoadAdError) {
        mInterstitialAd = null
      }

      override fun onAdLoaded(interstitialAd: InterstitialAd) {
        mInterstitialAd = interstitialAd
      }
    })
}

Unity

void LoadAdUnit() {

  // Note that you may want to encode and parse two sets of ad unit IDs for
  // Android / iOS in the Unity implementation.
  String adUnitId = remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue;
  this.interstitial = new InterstitialAd(adUnitId);
}

加入其他參數值檢查

應用程式程式碼的其他部分需要檢查 這個 Remote Config 參數的值,決定用來觀看的廣告體驗 就會引發這個事件。舉例來說,您可以決定 是否要在使用者 當前檢視完畢

應先發出擷取和啟用呼叫,才能取得任何參數值 (例如決定結束實驗或建立新實驗)。

您隨時可以使用 下列呼叫:

Swift

remoteConfig["INTERSTITIAL_AD_KEY"].stringValue

目標-C

self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;

Java

mFirebaseRemoteConfig.getString(INTERSTITIAL_AD_KEY)

Kotlin+KTX

remoteConfig.getString(INTERSTITIAL_AD_KEY)

Unity

remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue

根據每筆呼叫,這些呼叫一律為應用程式例項傳回相同的值: 無論廣告活動是放在控制組還是新的廣告變化版本群組中 但如果在 Firebase 控制台中發生任何變更,且已擷取且 啟用。




步驟 2:在 Firebase 控制台中設定 A/B 版本測試 步驟 4:開始 A/B 版本測試,查看測試結果