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

開始使用 Firebase 遠程配置


您可以使用 Firebase Remote Config 在您的應用程序中定義參數並在雲端更新它們的值,從而允許您修改應用程序的外觀和行為而無需分發應用程序更新。本指南將引導您完成入門步驟並提供一些示例代碼,所有這些代碼都可以從firebase/quickstart-android GitHub 存儲庫中克隆或下載。

第 1 步:將 Firebase 和 Remote Config SDK 添加到您的應用

  1. 如果您還沒有,請將 Firebase 添加到您的 Android 項目中

  2. 對於 Remote Config,需要 Google Analytics 才能將應用程序實例有條件地定位到用戶屬性和受眾。確保在項目中啟用 Google Analytics

  3. 在您的模塊(應用級)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:32.1.0')
    
        // 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.4.0'
        implementation 'com.google.firebase:firebase-analytics-ktx:21.3.0'
    }
    

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // 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.4.0'
        implementation 'com.google.firebase:firebase-analytics:21.3.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 後端之前按預期運行,並且如果沒有在後端設置默認值,則默認值可用。

  1. 使用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 控制台

    1. Parameters選項卡中,打開 Menu ,然後選擇Download default values

    2. 出現提示時,為 Android 啟用 .xml ,然後單擊下載文件

  2. 使用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 控制台步驟。

  1. Firebase 控制台中,打開您的項目。
  2. 從菜單中選擇遠程配置以查看遠程配置儀表板。
  3. 使用與您在應用程序中定義的參數相同的名稱定義參數。對於每個參數,您可以設置一個默認值(最終會覆蓋相應的應用內默認值),您還可以設置條件值。要了解更多信息,請參閱遠程配置參數和條件

第 6 步:獲取並激活值

  1. 要從遠程配置後端獲取參數值,請調用fetch()方法。您在後端設置的任何值都將被提取並存儲在遠程配置對像中。
  2. 要使獲取的參數值對您的應用程序可用,請調用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();
                }
            });

由於這些更新的參數值會影響應用的行為和外觀,因此您應該在確保用戶流暢體驗的時間激活獲取的值,例如用戶下次打開您的應用時。有關更多信息和示例,請參閱遠程配置加載策略

第 7 步:實時收聽更新

獲取參數值後,您可以使用實時 Remote Config 來監聽來自 Remote Config 後端的更新。實時遠程配置在更新可用時向連接的設備發出信號,並在您發布新的遠程配置版本後自動獲取更改。

Firebase SDK for Android v21.3.0+ (Firebase BoM v31.2.4+) 支持實時更新。

  1. 在您的應用程序中,使用addOnConfigUpdateListener()開始偵聽更新並自動獲取任何新參數值。實施onUpdate()回調以激活更新的配置。

    Kotlin+KTX

    remoteConfig.addOnConfigUpdateListener(object : ConfigUpdateListener {
        override fun onUpdate(configUpdate : ConfigUpdate) {
           Log.d(TAG, "Updated keys: " + configUpdate.updatedKeys);
    
           if (configUpdate.updatedKeys.contains("welcome_message")) {
               remoteConfig.activate().addOnCompleteListener {
                   displayWelcomeMessage()
               }
           }
        }
    
        override fun onError(error : FirebaseRemoteConfigException) {
            Log.w(TAG, "Config update error with code: " + error.code, error)
        }
    })
    

    Java

    mFirebaseRemoteConfig.addOnConfigUpdateListener(new ConfigUpdateListener() {
        @Override
        public void onUpdate(ConfigUpdate configUpdate) {
            Log.d(TAG, "Updated keys: " + configUpdate.getUpdatedKeys());
    
            mFirebaseRemoteConfig.activate().addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    displayWelcomeMessage();
                }
            });
        }
    
        @Override
        public void onError(FirebaseRemoteConfigException error) {
            Log.w(TAG, "Config update error with code: " + error.getCode(), error);
        }
    });
    
  2. 下次您發布新版本的遠程配置時,運行您的應用程序並偵聽更改的設備將調用ConfigUpdateListener

節流

如果應用程序在短時間內獲取的次數太多,獲取調用將受到限制並且 SDK 返回FirebaseRemoteConfigFetchThrottledException 。在 SDK 版本 17.0.0 之前,限制是在 60 分鐘的窗口中有 5 個提取請求(較新的版本有更寬鬆的限制)。

在應用程序開發期間,您可能希望非常頻繁地(每小時多次)獲取和激活配置,以便在開發和測試應用程序時快速迭代。在服務器上更新配置時,實時遠程配置更新會自動繞過緩存。為了適應最多 10 名開發人員的項目的快速迭代,您可以在您的應用中臨時設置一個具有較低最小提取間隔 ( setMinimumFetchIntervalInSeconds ) 的FirebaseRemoteConfigSettings對象。

Remote Config 的默認最小提取間隔為 12 小時,這意味著在 12 小時的窗口中不會從後端提取配置超過一次,無論實際進行了多少次提取調用。具體來說,最小獲取間隔按以下順序確定:

  1. fetch(long)中的參數
  2. FirebaseRemoteConfigSettings.setMinimumFetchIntervalInSeconds(long)中的參數
  3. 默認值 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: