Select Page

Firebase Remote Config is a cloud service that will allow you to define parameters and their values in the cloud, consumes it in your client application on the fly and also cache them for efficient retrieval. This caching mechanism is very useful when you required to do quick changes to the app without making an update on Playstore.

As per the official documentation by default the cache expires after 12 hours, but you can change the cache expiration for a specific fetch by passing the desired cache expiration to the fetch method.

You can also publish updates for a segment of user base, it allows you to change your selected parameter for segmented users, based on the application versions, audience groups from Firebase Analytics, user language and more.

Overview of what we are going to implement!

We are going save the latest version code of app, and the update dialog message in Firebase Remote Config console and fetch the value when the user launch the app. Check if the fetched version code is greater than the current version code of app or not. If it is, then show a dialog with the message retrieved from remote config. That’s it.

Remote Config Sample Output

Implementation of Firebase Remote Config in Android is very easy. In this tutorial, I’ll show you how to use Remote Config in Android apps. All setup and ready to go with remote configuration. I will try to be as much detailed as possible, and will break down this tutorial to multiple steps for better understanding.

Let’s get started!

  1. Firebase and Remote Config SDK setup
  2. Setting in-app default parameter values
  3. Setting server-side parameter values
  4. Retrieving parameter values ​​from server-side

1. Firebase and Remote Config SDK setup

Using Firebase Assistant, you can easily complete this setup by selecting
the option “Set Up Remote Config” from the Assistant window which can be open by Tools > Firebase and the needed library will be automatically added.

remote_config_setup_assistant_banner

Once done, you can then access the FirebaseRemoteConfig instance throughout your application where required.

2. Setting in-app default parameter values

In Remote Config you can define key-value pairs which are known as parameters. These parameters will be used in your client app.

Key — used to define the identify for the parameter
Value — used to represent the value of the defined parameter.

Create and initialise a default HashMap, values will be served from this HashMap until a fetch request is completed

// To get the version code from the auto generated file
final int versionCode = BuildConfig.VERSION_CODE;
// Hashmap which contains the default values for all the parameter defined in the remote config server
final HashMap<String, Object> defaultMap = new HashMap<>();
defaultMap.put(FB_RC_KEY_TITLE, "Update Available");
defaultMap.put(FB_RC_KEY_DESCRIPTION, "A new version of the application is available please click below to update the latest version.");
defaultMap.put(FB_RC_KEY_FORCE_UPDATE_VERSION, ""+versionCode);
defaultMap.put(FB_RC_KEY_LATEST_VERSION, ""+versionCode);
// Instance to access the remote config parameters
FirebaseRemoteConfig mFirebaseRemoteConfig;
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// To set the default values for the remote config parameters
mFirebaseRemoteConfig.setDefaults(defaultMap);

Note: If this default value is not defined then no value is returned when requested.

3. Setting server-side parameter values

Add the parameters in Firebase Console.

Once you’ve opened the Firebase console, you’ll see two text fields:

“Parameter key” and “Default value” which you have to fill in and finally you should not forget to make “PUBLISH “to save your changes., otherwise it will not work.

After publishing, changed values will be updated according to server-side and client-side priorities list.

Remote config publish changes

4. Retrieving parameter values ​​from server-side

After seeing up everything successfully, you need to fetch the data from the firebase console.

For this you can call the fetch method and add an onCompleteListener which will be called the fetch process is complete. Not only this, but you also need to check if the task (fetching process) was successful or not.

So here you go.

Task<Void> fetchTask=mFirebaseRemoteConfig.fetch(BuildConfig.DEBUG?0: TimeUnit.HOURS.toSeconds(4));
fetchTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// After config data is successfully fetched, it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
String title=getValue(FB_RC_KEY_TITLE,defaultMap);
String description=getValue(FB_RC_KEY_DESCRIPTION,defaultMap);
int forceUpdateVersion= Integer.parseInt(getValue(FB_RC_KEY_FORCE_UPDATE_VERSION,defaultMap));
int latestAppVersion= Integer.parseInt(getValue(FB_RC_KEY_LATEST_VERSION,defaultMap));
} else {
Toast.makeText(HomeActivity.this, "Fetch Failed",Toast.LENGTH_SHORT).show();
}
}
});

As I mentioned earlier, Remote Config caches values locally after the first successful fetch request. and also you can change the cache expiration for a specific request by passing the desired cache expiration. If you reduce this expiration time to a very small value, you might start hitting the client-side throttling limit.

You can increase the client-side quota by enabling developer mode.Just paste the source code below to getInstance along with developer mode.

// Instance to access the remote config parameters
FirebaseRemoteConfig mFirebaseRemoteConfig;
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// To enable the developer mode
mFirebaseRemoteConfig.setConfigSettings(new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG).build());

conditional values:

You can effortlessly set how a segment behaves or looks in our application based on the user / device that is using it. You can add several conditions in one parameter. For example, you can change the force update flag as true only for the Indian users .

In addition, if you have more than one condition in a parameter, then the Remote Config selects the corresponding condition in the order.

Conditional_statement

Force update logical implementation:

After retrieving the key-values from the remote config, you need to check the installed app version, and compare the current app version which is received from the remote config server.

You can get the version code from BuildConfig.java. But notice, that if you’ll access this values in library it will return library version, not apps one, that uses this library. So use only in non-library projects!

I think it is clear to understand how to implement this from following code snippets with comment lines.

if(latestAppVersion>versionCode){
if(forceUpdateVersion>versionCode)
isCancelable=false;
// App update dialog view instance, used to show the dialog with the received values
AppUpdateDialog appUpdateDialog;
appUpdateDialog = new AppUpdateDialog(HomeActivity.this, title, description, isCancelable);
appUpdateDialog.setCancelable(false);
appUpdateDialog.show();
Window window = appUpdateDialog.getWindow();
assert window != null;
window.setLayout(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
}

How long to wait?

In case it is not possible to connect to the Internet, the Remote Config will retrieve the config from the cache. If no cache is available, the default config will be retrieved within the application.

Limitations:

2000 → Max parameters count
300 → Remote config templates with 90 day lifetime for template
500 → Max conditions count
256 → Max chars length of one parameter key
800.000 → Max chars for total parameters values
_ / A-Z / a-z → Parameter keys have to start with
0–9 → Parameter keys may contains

Note:

So whenever you release a new app, you need to put that latest version code in Firebase Remote Config Console.

One more thing to do, before executing the project you have to change the google-services.json file.

The source code is available on GitHub, use the below links to get the application.

View on GithubDownload .zip

Feel free to comment and share, keep watching this space get more updates on Android Stuff!

Elsewhere

Jaison Fernando

Android Developer at NFN Labs
Elsewhere