步驟 3:在應用程式程式碼中處理 Remote Config 參數值
前言:使用 Firebase 調整AdMob廣告展示頻率 |
步驟 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'
Objective-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:24.5.0' implementation 'com.google.firebase:firebase-analytics:23.0.0' implementation 'com.google.firebase:firebase-config:23.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
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"); }
擷取並啟用 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() }
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(); });
此時應用程式就可以處理在 A/B 測試設定中建立的 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.
Objective-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
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
Objective-C
self.remoteConfig[@"INTERSTITIAL_AD_KEY"].stringValue;
Java
mFirebaseRemoteConfig.getString(INTERSTITIAL_AD_KEY)
Kotlin
remoteConfig.getString(INTERSTITIAL_AD_KEY)
Unity
remoteConfig.GetValue("INTERSTITIAL_AD_KEY").StringValue
視應用程式執行個體置於控制組或其中一個新廣告變化版本群組而定,這些呼叫一律會傳回相同的值 (除非先前的呼叫擷取並啟用了 Firebase 控制台中的任何變更)。
Firebase 控制台中設定 A/B 測試 步驟 2:在 步驟 4:啟動 A/B 測試並查看測試結果