步驟 3:在應用程式的程式碼中處理遠端設定參數值
簡介:使用 Firebase 調整 AdMob 廣告展示頻率 |
步驟 1:使用 AdMob 建立新的廣告單元變化版本進行測試 |
步驟 2:在 Firebase 控制台中設定 A/B 測試 |
步驟 3:在應用程式的程式碼中處理遠端設定參數值 |
步驟 4:在 Firebase 控制台中開始 A/B 版本測試並查看測試結果 |
步驟 5:決定是否要採用新的廣告格式 |
在最後一個步驟結束時,您已建立遠端設定參數 (INTERSTITIAL_AD_KEY
)。在這個步驟中,您要在應用程式的程式碼中加入邏輯,讓應用程式根據該參數值顯示的內容。
新增必要的 SDK
在應用程式程式碼中使用遠端設定之前,請將遠端設定 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.1.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
設定遠端設定執行個體
如要使用遠端設定參數值,請設定遠端設定執行個體,使其設定為擷取用戶端應用程式執行個體的新值。
在這個範例中,遠端設定已設為每小時檢查一次新的參數值。
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");
}
擷取並啟用遠端設定
擷取並啟用遠端設定參數,讓其開始使用新的參數值。
您需要盡早在應用程式的載入階段發出此呼叫,因為這是非同步呼叫,而您需要預先擷取遠端設定值,應用程式才能知道要顯示哪則廣告。
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();
});
您的應用程式現在已準備好處理,在 A/B 測試設定期間建立的遠端設定參數 (如本教學課程稍早的設定步驟)。
使用遠端設定參數值
使用 loadAdUnit()
函式中的預先擷取遠端設定值,決定要在此應用程式執行個體顯示哪個廣告展示頻率變化版本。
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);
}
加入其他參數值檢查
您需要在應用程式程式碼中的其他區域檢查這個遠端設定參數的值,再決定要載入哪個廣告體驗。舉例來說,您可以決定當使用者看完目前廣告後,是否要重新載入廣告。
您必須先發出擷取和啟用呼叫,才能取得任何參數值異動,例如決定結束實驗或建立新實驗。
接著,您可隨時使用下列呼叫檢查參數的值:
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 版本測試並查看測試結果