Za pomocą Firebase Remote Config możesz definiować parametry w swojej aplikacji i aktualizować ich wartości w chmurze, co pozwala modyfikować wygląd i zachowanie aplikacji bez rozpowszechniania aktualizacji aplikacji. Ten przewodnik przeprowadzi Cię przez kolejne kroki i zawiera przykładowy kod, który można sklonować lub pobrać z repozytorium GitHub Firebase/quickstart-Android .
Krok 1: Dodaj Firebase i pakiet SDK do zdalnej konfiguracji do swojej aplikacji
Jeśli jeszcze tego nie zrobiłeś, dodaj Firebase do swojego projektu na Androida .
W przypadku zdalnej konfiguracji wymagana jest usługa Google Analytics do warunkowego kierowania instancji aplikacji na właściwości użytkownika i odbiorców. Upewnij się, że masz włączoną usługę Google Analytics w swoim projekcie.
W pliku Gradle modułu (na poziomie aplikacji) (zwykle
<project>/<app-module>/build.gradle.kts
lub<project>/<app-module>/build.gradle
) dodaj zależność dla Remote Config Biblioteka Androida. Zalecamy używanie Firebase Android BoM do kontrolowania wersji bibliotek.Ponadto w ramach konfigurowania Analytics musisz dodać do swojej aplikacji pakiet SDK Firebase dla Google Analytics.
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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") }
Korzystając z Firebase Android BoM , Twoja aplikacja będzie zawsze korzystać z kompatybilnych wersji bibliotek Firebase Android.
(Alternatywa) Dodaj zależności biblioteki Firebase bez użycia BoM
Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.
Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy używanie BoM do zarządzania wersjami bibliotek, co gwarantuje, że wszystkie wersje będą kompatybilne.
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.1") 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.3.1")) // 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") }
Korzystając z Firebase Android BoM , Twoja aplikacja będzie zawsze korzystać z kompatybilnych wersji bibliotek Firebase Android.
(Alternatywa) Dodaj zależności biblioteki Firebase bez użycia BoM
Jeśli zdecydujesz się nie używać BoM Firebase, musisz określić każdą wersję biblioteki Firebase w jej wierszu zależności.
Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy używanie BoM do zarządzania wersjami bibliotek, co gwarantuje, że wszystkie wersje będą kompatybilne.
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.1") implementation("com.google.firebase:firebase-analytics:21.3.0") }
Krok 2: Pobierz pojedynczy obiekt Remote Config
Pobierz instancję obiektu Remote Config i ustaw minimalny interwał pobierania, aby umożliwić częste odświeżanie:
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);
Obiekt singleton służy do przechowywania domyślnych wartości parametrów w aplikacji, pobierania zaktualizowanych wartości parametrów z zaplecza i kontrolowania, kiedy pobrane wartości są udostępniane aplikacji.
Podczas opracowywania zaleca się ustawienie stosunkowo niskiego minimalnego interwału pobierania. Aby uzyskać więcej informacji, zobacz Ograniczanie .
Krok 3: Ustaw domyślne wartości parametrów w aplikacji
Możesz ustawić domyślne wartości parametrów w aplikacji w obiekcie Remote Config, tak aby aplikacja zachowywała się zgodnie z oczekiwaniami przed połączeniem się z backendem Remote Config i aby dostępne były wartości domyślne, jeśli w backendzie nie ustawiono żadnych wartości.
Zdefiniuj zestaw nazw parametrów i domyślnych wartości parametrów, korzystając z obiektu Map lub pliku zasobów XML przechowywanego w folderze
res/xml
aplikacji. Przykładowa aplikacja szybkiego startu Remote Config używa pliku XML do definiowania domyślnych nazw i wartości parametrów.Jeśli wartości parametrów zaplecza usługi Remote Config zostały już skonfigurowane, możesz pobrać wygenerowany plik XML zawierający wszystkie wartości domyślne i zapisać go w katalogu
res/xml
aplikacji:ODPOCZYNEK
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
Konsola Firebase
Na karcie Parametry otwórz menu i wybierz opcję Pobierz wartości domyślne .
Po wyświetleniu monitu włącz plik .xml dla systemu Android , a następnie kliknij opcję Pobierz plik .
Dodaj te wartości do obiektu Remote Config za pomocą
setDefaultsAsync(int)
, jak pokazano:Kotlin+KTX
remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
Java
mFirebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Krok 4: Uzyskaj wartości parametrów do wykorzystania w swojej aplikacji
Teraz możesz uzyskać wartości parametrów z obiektu Remote Config. Jeśli ustawisz wartości w backendie, pobierzesz je, a następnie aktywujesz, te wartości będą dostępne dla Twojej aplikacji. W przeciwnym razie wartości parametrów w aplikacji zostaną skonfigurowane przy użyciu setDefaultsAsync(int)
. Aby uzyskać te wartości, wywołaj poniższą metodę, która odwzorowuje typ danych oczekiwany przez Twoją aplikację, podając klucz parametru jako argument:
Krok 5: Ustaw wartości parametrów w zapleczu zdalnej konfiguracji
Korzystając z konsoli Firebase lub interfejsów API zaplecza Remote Config , możesz utworzyć nowe wartości domyślne po stronie serwera, które zastępują wartości w aplikacji zgodnie z żądaną logiką warunkową lub kierowaniem na użytkownika. W tej sekcji opisano kroki konsoli Firebase umożliwiające utworzenie tych wartości.
- W konsoli Firebase otwórz swój projekt.
- Wybierz opcję Zdalna konfiguracja z menu, aby wyświetlić pulpit nawigacyjny Zdalnej konfiguracji.
- Zdefiniuj parametry o takich samych nazwach, jak parametry zdefiniowane w aplikacji. Dla każdego parametru możesz ustawić wartość domyślną (która ostatecznie zastąpi odpowiednią wartość domyślną w aplikacji), możesz także ustawić wartości warunkowe. Aby dowiedzieć się więcej, zobacz Parametry i warunki zdalnej konfiguracji .
Krok 6: Pobierz i aktywuj wartości
- Aby pobrać wartości parametrów z zaplecza Remote Config, wywołaj metodę
fetch()
. Wszelkie wartości ustawione w backendie są pobierane i przechowywane w obiekcie Remote Config. Aby udostępnić aplikacji pobrane wartości parametrów, wywołaj metodę
activate()
.W przypadkach, gdy chcesz pobrać i aktywować wartości w jednym wywołaniu, możesz użyć żądania
fetchAndActivate()
w celu pobrania wartości z zaplecza zdalnej konfiguracji i udostępnienia ich aplikacji: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(); } });
Ponieważ te zaktualizowane wartości parametrów wpływają na zachowanie i wygląd aplikacji, należy aktywować pobrane wartości w czasie zapewniającym użytkownikowi bezproblemową obsługę, na przykład przy następnym otwarciu aplikacji. Więcej informacji i przykładów można znaleźć w artykule Strategie ładowania zdalnej konfiguracji .
Krok 7: Słuchaj aktualizacji w czasie rzeczywistym
Po pobraniu wartości parametrów można używać funkcji Remote Config w czasie rzeczywistym do nasłuchiwania aktualizacji z zaplecza Remote Config. Zdalna konfiguracja w czasie rzeczywistym sygnalizuje podłączonym urządzeniom dostępność aktualizacji i automatycznie pobiera zmiany po opublikowaniu nowej wersji Zdalnej konfiguracji.
Aktualizacje w czasie rzeczywistym są obsługiwane przez pakiet SDK Firebase dla Androida w wersji 21.3.0+ (Firebase BoM v31.2.4+).
W swojej aplikacji użyj
addOnConfigUpdateListener()
, aby rozpocząć nasłuchiwanie aktualizacji i automatycznie pobierać nowe wartości parametrów. Zaimplementuj wywołanie zwrotneonUpdate()
, aby aktywować zaktualizowaną konfigurację.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); } }); Następnym razem, gdy opublikujesz nową wersję zdalnej konfiguracji, urządzenia, na których działa Twoja aplikacja i nasłuchują zmian, wywołają
ConfigUpdateListener
.
Dławienie
Jeśli aplikacja zostanie pobrana zbyt wiele razy w krótkim czasie, wywołania pobierania zostaną ograniczone, a zestaw SDK zwróci FirebaseRemoteConfigFetchThrottledException
. Przed wersją SDK 17.0.0 limit wynosił 5 żądań pobrania w 60-minutowym oknie (nowsze wersje mają bardziej liberalne limity).
Podczas tworzenia aplikacji możesz chcieć bardzo często pobierać i aktywować konfiguracje (wiele razy na godzinę), aby móc szybko wykonywać iteracje podczas opracowywania i testowania aplikacji. Aktualizacje zdalnej konfiguracji w czasie rzeczywistym automatycznie omijają pamięć podręczną, gdy konfiguracja jest aktualizowana na serwerze. Aby umożliwić szybką iterację projektu z maksymalnie 10 programistami, możesz tymczasowo ustawić w swojej aplikacji obiekt FirebaseRemoteConfigSettings
z niskim minimalnym interwałem pobierania ( setMinimumFetchIntervalInSeconds
).
Domyślny minimalny interwał pobierania dla Zdalnej konfiguracji wynosi 12 godzin, co oznacza, że konfiguracje nie będą pobierane z zaplecza częściej niż raz w ciągu 12 godzin, niezależnie od liczby faktycznie wykonanych wywołań pobierania. W szczególności minimalny interwał pobierania jest określany w następującej kolejności:
- Parametr w
fetch(long)
- Parametr w
FirebaseRemoteConfigSettings.setMinimumFetchIntervalInSeconds(long)
- Wartość domyślna to 12 godzin
Aby ustawić minimalny interwał pobierania na wartość niestandardową, użyj FirebaseRemoteConfigSettings.Builder.setMinimumFetchIntervalInSeconds(long)
.
Next steps
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.kts
or<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:32.3.1")) // 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.4.1") 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.3.1")) // 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.4.1") implementation("com.google.firebase:firebase-analytics:21.3.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.
Step 7: Listen for updates in real time
After you fetch parameter values, you can use real-time Remote Config to listen for updates from the Remote Config backend. Real-time Remote Config signals to connected devices when updates are available and automatically fetches the changes after you publish a new Remote Config version.
Real-time updates are supported by the Firebase SDK for Android v21.3.0+ (Firebase BoM v31.2.4+).
In your app, use
addOnConfigUpdateListener()
to start listening for updates and automatically fetch any new parameter values. Implement theonUpdate()
callback to activate the updated config.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); } }); The next time you publish a new version of your Remote Config, devices that are running your app and listening for changes will call the
ConfigUpdateListener
.
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. Real-time Remote Config updates automatically bypass the cache when the config is updated on the server. 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)
.
Next steps
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: