您可以使用 Firebase Remote Config 在您的應用程序中定義參數並在雲端更新它們的值,從而允許您修改應用程序的外觀和行為而無需分發應用程序更新。本指南將引導您完成入門步驟並提供一些示例代碼,所有這些代碼都可以從firebase/quickstart-android GitHub 存儲庫中克隆或下載。
第 1 步:將 Firebase 和 Remote Config SDK 添加到您的應用
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
對於 Remote Config,需要 Google Analytics 才能將應用程序實例有條件地定位到用戶屬性和受眾。確保在項目中啟用 Google Analytics 。
在您的模塊(應用級)Gradle 文件(通常為
<project>/<app-module>/build.gradle
)中,添加 Remote Config Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。此外,作為設置 Analytics 的一部分,您需要將適用於 Google Analytics 的 Firebase SDK 添加到您的應用中。
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // Add the dependencies for the Remote Config and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config-ktx' implementation 'com.google.firebase:firebase-analytics-ktx' }
通過使用Firebase Android BoM ,您的應用將始終使用兼容版本的 Firebase Android 庫。
(備選)在不使用 BoM 的情況下添加 Firebase 庫依賴項
如果您選擇不使用 Firebase BoM,則必須在其依賴項行中指定每個 Firebase 庫版本。
請注意,如果您在應用中使用多個Firebase 庫,我們強烈建議您使用 BoM 來管理庫版本,以確保所有版本都兼容。
dependencies { // Add the dependencies for the Remote Config and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config-ktx:21.2.1' implementation 'com.google.firebase:firebase-analytics-ktx:21.2.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // Add the dependencies for the Remote Config and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config' implementation 'com.google.firebase:firebase-analytics' }
通過使用Firebase Android BoM ,您的應用將始終使用兼容版本的 Firebase Android 庫。
(備選)在不使用 BoM 的情況下添加 Firebase 庫依賴項
如果您選擇不使用 Firebase BoM,則必須在其依賴項行中指定每個 Firebase 庫版本。
請注意,如果您在應用中使用多個Firebase 庫,我們強烈建議您使用 BoM 來管理庫版本,以確保所有版本都兼容。
dependencies { // Add the dependencies for the Remote Config and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config:21.2.1' implementation 'com.google.firebase:firebase-analytics:21.2.0' }
第 2 步:獲取 Remote Config 單例對象
獲取遠程配置對象實例並設置最小獲取間隔以允許頻繁刷新:
Kotlin+KTX
val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings)
Java
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setMinimumFetchIntervalInSeconds(3600) .build(); mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
單例對像用於存儲應用內默認參數值、從後端獲取更新的參數值,以及控制獲取的值何時可用於您的應用。
在開發過程中,建議設置一個相對較低的最小獲取間隔。有關詳細信息,請參閱節流。
第 3 步:設置應用內默認參數值
您可以在 Remote Config 對像中設置應用內默認參數值,以便您的應用在連接到 Remote Config 後端之前按預期運行,並且如果沒有在後端設置默認值,則默認值可用。
使用Map對像或存儲在應用程序的
res/xml
文件夾中的XML 資源文件定義一組參數名稱和默認參數值。 Remote Config 快速入門示例應用程序使用XML 文件來定義默認參數名稱和值。如果您已經配置了 Remote Config 後端參數值,您可以下載包含所有默認值的生成的 XML 文件並將其保存到應用程序的
res/xml
目錄:休息
curl --compressed -D headers -H "Authorization: Bearer token -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=XML -o remote_config_defaults.xml
Firebase 控制台
在Parameters選項卡中,打開 Menu ,然後選擇Download default values 。
出現提示時,為 Android 啟用 .xml ,然後單擊下載文件。
使用
setDefaultsAsync(int)
將這些值添加到遠程配置對象,如下所示:Kotlin+KTX
remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
第 4 步:獲取要在您的應用中使用的參數值
現在您可以從 Remote Config 對像中獲取參數值。如果您在後端設置值,獲取它們,然後激活它們,那麼這些值可用於您的應用程序。否則,您將獲得使用setDefaultsAsync(int)
配置的應用內參數值。要獲取這些值,請調用下面列出的映射到您的應用程序期望的數據類型的方法,並提供參數鍵作為參數:
第 5 步:在 Remote Config 後端設置參數值
使用 Firebase 控制台或遠程配置後端 API ,您可以創建新的服務器端默認值,根據您所需的條件邏輯或用戶定位覆蓋應用內值。本節介紹創建這些值的 Firebase 控制台步驟。
- 在Firebase 控制台中,打開您的項目。
- 從菜單中選擇遠程配置以查看遠程配置儀表板。
- 使用與您在應用程序中定義的參數相同的名稱定義參數。對於每個參數,您可以設置一個默認值(最終會覆蓋相應的應用內默認值),您還可以設置條件值。要了解更多信息,請參閱遠程配置參數和條件。
第 6 步:獲取並激活值
- 要從遠程配置後端獲取參數值,請調用
fetch()
方法。您在後端設置的任何值都將被提取並存儲在遠程配置對像中。 要使獲取的參數值對您的應用程序可用,請調用
activate()
方法。對於您希望在一次調用中獲取和激活值的情況,您可以使用
fetchAndActivate()
請求從遠程配置後端獲取值並將它們提供給應用程序:Kotlin+KTX
remoteConfig.fetchAndActivate() .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val updated = task.result Log.d(TAG, "Config params updated: $updated") Toast.makeText(this, "Fetch and activate succeeded", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Fetch failed", Toast.LENGTH_SHORT).show() } displayWelcomeMessage() }
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); Toast.makeText(MainActivity.this, "Fetch and activate succeeded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Fetch failed", Toast.LENGTH_SHORT).show(); } displayWelcomeMessage(); } });
由於這些更新的參數值會影響應用的行為和外觀,因此您應該在確保用戶流暢體驗的時間激活獲取的值,例如用戶下次打開您的應用時。有關更多信息和示例,請參閱遠程配置加載策略。
節流
如果應用程序在短時間內獲取的次數太多,獲取調用將受到限制並且 SDK 返回FirebaseRemoteConfigFetchThrottledException
。在 SDK 版本 17.0.0 之前,限制是在 60 分鐘的窗口中有 5 個提取請求(較新的版本有更寬鬆的限制)。
在應用程序開發期間,您可能希望非常頻繁地(每小時多次)獲取和激活配置,以便在開發和測試應用程序時快速迭代。為了適應最多 10 名開發人員的項目的快速迭代,您可以在您的應用中臨時設置一個具有較低最小提取間隔 ( setMinimumFetchIntervalInSeconds
) 的FirebaseRemoteConfigSettings
對象。
Remote Config 的默認最小提取間隔為 12 小時,這意味著在 12 小時的窗口中不會從後端提取配置超過一次,無論實際進行了多少次提取調用。具體來說,最小獲取間隔按以下順序確定:
-
fetch(long)
中的參數 FirebaseRemoteConfigSettings.setMinimumFetchIntervalInSeconds(long)
中的參數- 默認值 12 小時
要將最小提取間隔設置為自定義值,請使用FirebaseRemoteConfigSettings.Builder.setMinimumFetchIntervalInSeconds(long)
。
下一步
If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including:
,You can use Firebase Remote Config to define parameters in your app and update their values in the cloud, allowing you to modify the appearance and behavior of your app without distributing an app update. This guide walks you through the steps to get started and provides some sample code, all of which is available to clone or download from the firebase/quickstart-android GitHub repository.
Step 1: Add Firebase and the Remote Config SDK to your app
If you haven't already, add Firebase to your Android project .
For Remote Config, Google Analytics is required for the conditional targeting of app instances to user properties and audiences. Make sure that you enable Google Analytics in your project.
In your module (app-level) Gradle file (usually
<project>/<app-module>/build.gradle
), add the dependency for the Remote Config Android library. We recommend using the Firebase Android BoM to control library versioning.Also, as part of setting up Analytics, you need to add the Firebase SDK for Google Analytics to your app.
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // Add the dependencies for the Remote Config and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config-ktx' implementation 'com.google.firebase:firebase-analytics-ktx' }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using the BoM
If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Remote Config and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config-ktx:21.2.1' implementation 'com.google.firebase:firebase-analytics-ktx:21.2.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.3') // Add the dependencies for the Remote Config and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config' implementation 'com.google.firebase:firebase-analytics' }
By using the Firebase Android BoM , your app will always use compatible versions of Firebase Android libraries.
(Alternative) Add Firebase library dependencies without using the BoM
If you choose not to use the Firebase BoM, you must specify each Firebase library version in its dependency line.
Note that if you use multiple Firebase libraries in your app, we strongly recommend using the BoM to manage library versions, which ensures that all versions are compatible.
dependencies { // Add the dependencies for the Remote Config and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-config:21.2.1' implementation 'com.google.firebase:firebase-analytics:21.2.0' }
Step 2: Get the Remote Config singleton object
Get a Remote Config object instance and set the minimum fetch interval to allow for frequent refreshes:
Kotlin+KTX
val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig val configSettings = remoteConfigSettings { minimumFetchIntervalInSeconds = 3600 } remoteConfig.setConfigSettingsAsync(configSettings)
Java
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setMinimumFetchIntervalInSeconds(3600) .build(); mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings);
The singleton object is used to store in-app default parameter values, fetch updated parameter values from the backend, and control when fetched values are made available to your app.
During development, it's recommended to set a relatively low minimum fetch interval. See Throttling for more information.
Step 3: Set in-app default parameter values
You can set in-app default parameter values in the Remote Config object, so that your app behaves as intended before it connects to the Remote Config backend, and so that default values are available if none are set in the backend.
Define a set of parameter names and default parameter values using a Map object or an XML resource file stored in your app's
res/xml
folder. The Remote Config quickstart sample app uses an XML file to define default parameter names and values.If you have already configured Remote Config backend parameter values, you can download a generated XML file that includes all default values and save it to your app's
res/xml
directory:REST
curl --compressed -D headers -H "Authorization: Bearer token -X GET https://firebaseremoteconfig.googleapis.com/v1/projects/my-project-id/remoteConfig:downloadDefaults?format=XML -o remote_config_defaults.xml
Firebase console
In the Parameters tab, open the Menu , and select Download default values .
When prompted, enable .xml for Android , then click Download file .
Add these values to the Remote Config object using
setDefaultsAsync(int)
, as shown:Kotlin+KTX
remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Step 4: Get parameter values to use in your app
Now you can get parameter values from the Remote Config object. If you set values in the backend, fetch them, and then activate them, those values are available to your app. Otherwise, you get the in-app parameter values configured using setDefaultsAsync(int)
. To get these values, call the method listed below that maps to the data type expected by your app, providing the parameter key as an argument:
Step 5: Set parameter values in the Remote Config backend
Using the Firebase console or the Remote Config backend APIs , you can create new server-side default values that override the in-app values according to your desired conditional logic or user targeting. This section describes the Firebase console steps to create these values.
- In the Firebase console , open your project.
- Select Remote Config from the menu to view the Remote Config dashboard.
- Define parameters with the same names as the parameters that you defined in your app. For each parameter, you can set a default value (which will eventually override the corresponding in-app default value), and you can also set conditional values. To learn more, see Remote Config Parameters and Conditions .
Step 6: Fetch and activate values
- To fetch parameter values from the Remote Config backend, call the
fetch()
method. Any values that you set in the backend are fetched and stored in the Remote Config object. To make fetched parameter values available to your app, call the
activate()
method.For cases where you want to fetch and activate values in one call, you can use a
fetchAndActivate()
request to fetch values from the Remote Config backend and make them available to the app:Kotlin+KTX
remoteConfig.fetchAndActivate() .addOnCompleteListener(this) { task -> if (task.isSuccessful) { val updated = task.result Log.d(TAG, "Config params updated: $updated") Toast.makeText(this, "Fetch and activate succeeded", Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, "Fetch failed", Toast.LENGTH_SHORT).show() } displayWelcomeMessage() }
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); Toast.makeText(MainActivity.this, "Fetch and activate succeeded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Fetch failed", Toast.LENGTH_SHORT).show(); } displayWelcomeMessage(); } });
Because these updated parameter values affect the behavior and appearance of your app, you should activate the fetched values at a time that ensures a smooth experience for your user, such as the next time that the user opens your app. See Remote Config loading strategies for more information and examples.
Throttling
If an app fetches too many times in a short time period, fetch calls are throttled and the SDK returns FirebaseRemoteConfigFetchThrottledException
. Before SDK version 17.0.0, the limit was 5 fetch requests in a 60 minute window (newer versions have more permissive limits).
During app development, you might want to fetch and activate configs very frequently (many times per hour) to let you rapidly iterate as you develop and test your app. To accommodate rapid iteration on a project with up to 10 developers, you can temporarily set a FirebaseRemoteConfigSettings
object with a low minimum fetch interval ( setMinimumFetchIntervalInSeconds
) in your app.
The default minimum fetch interval for Remote Config is 12 hours, which means that configs won't be fetched from the backend more than once in a 12 hour window, regardless of how many fetch calls are actually made. Specifically, the minimum fetch interval is determined in this following order:
- The parameter in
fetch(long)
- The parameter in
FirebaseRemoteConfigSettings.setMinimumFetchIntervalInSeconds(long)
- The default value of 12 hours
To set the minimum fetch interval to a custom value, use FirebaseRemoteConfigSettings.Builder.setMinimumFetchIntervalInSeconds(long)
.
下一步
If you haven't already, explore the Remote Config use cases , and take a look at some of the key concepts and advanced strategies documentation, including: