A Firebase Remote Config Tutorial

PreviousTable of ContentsNext
Firebase Remote ConfigFirebase Analytics



In this chapter of Firebase Essentials, an example Android Studio project will be created with the objective of demonstrating the use of Firebase Remote Config to remotely change a number of configuration options within an Android app.

Creating the Project

The app created in this chapter will use Firebase Remote Config to allow the background color, text and font size of components within a user interface to be modified via the Firebase console.

Begin by starting Android Studio and selecting the Start a new Android Studio project quick start option from the welcome screen.

Within the new project dialog, enter RemoteConfig into the Application name field and your domain as the Company Domain setting before clicking on the Next button.

On the form factors screen, enable the Phone and Tablet option and set the minimum SDK to API 16: Android 4.1 (Jellybean). Continue through the screens, requesting the creation of an Empty Activity named RemoteConfigActivity with a corresponding layout named activity_remote_config.

Adding Remote Config Support to the Project

In order to make use of Remote Config the project needs to be registered with a Firebase project and configured with the appropriate Remote Config libraries. Within the Android Studio main window, select the Tools -> Firebase menu option to display the Firebase assistant panel. Within the panel locate and unfold the Remote Config section and click on the Set up Firebase Remote Config link. On the Remote Config setup screen, click on the Connect to Firebase button and, in the resulting dialog, select the Firebase Examples project from the list of existing projects before clicking on the Connect to Firebase button.

After the project has been connected to Firebase, click on the Add Remote Config to your app button in the Firebase assistant panel followed by the Accept Changes button in the configuration dialog.


Designing the User Interface

Once the project has been created, open the activity_remote_config.xml layout file in the layout editor tool and drag and drop a Button widget onto the layout so that it is positioned beneath the existing “Hello World” TextView as shown in Figure 37‑1 below:


Remote config ui.png

Figure 37‑1


Select the Button widget and, using the Properties tool window, set the text property to “Update Config” and configure the onClick property to call a method named updateConfig. Select the TextView widget and change the ID property to welcomeText.

Select the ConstraintLayout entry in the Component Tree tool window (Figure 37‑2) and change the ID of the layout in the properties panel to layout.


Remote config constraint layout.png

Figure 37‑2


Finally, click on the Infer Constraints button (Figure 37‑3) in the toolbar to add appropriate constraints to the layout.


Remote config infer constraints.png

Figure 37‑3

Declaring the Default In-App Parameters

The in-app parameters for the project will be contained within an XML resource file which now needs to be added to the project. Within the Project tool window, locate and right-click on the app -> res folder and select the New -> Android Resource Directory menu option. In the resulting dialog, enter xml into the directory name field and select xml for the resource type before clicking on the OK button:


Remote config new resource directory.png

Figure 37‑4


After the xml directory has been created it will appear in the Project tool window. Right-click on the new directory, this time selecting the New –> File menu option. In the new file dialog, specify remote_config_params.xml as the filename before clicking on the OK button to create the file.

Load the new XML resource file into the editor and modify it to declare the default in-app parameters as follows:

<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
    <entry>
        <key>welcome_text</key>
        <value>Welcome to Firebase</value>
    </entry>
    <entry>
        <key>welcome_font_size</key>
        <value>16</value>
    </entry>
    <entry>
        <key>main_background_color</key>
        <value>#42f486</value>
    </entry>
</defaultsMap>

Loading the Config Parameters

Code now needs to be added to the main activity class to obtain a FirebaseRemoteConfig object reference and to load into it the default in-app parameters from the XML resource file. Open the RemoteConfigActivity.java file and modify the code so that it reads as follows. Note that a number of import directives are also added in preparation for later additions to the class:

package com.ebookfrenzy.remoteconfig;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;

public class RemoteConfigActivity extends AppCompatActivity {

    private FirebaseRemoteConfig fbRemoteConfig;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_config);

        fbRemoteConfig = FirebaseRemoteConfig.getInstance();
        fbRemoteConfig.setDefaults(R.xml.remote_config_params);

        fbRemoteConfig.setConfigSettings(
             new FirebaseRemoteConfigSettings.Builder()
                .setDeveloperModeEnabled(true)
                .build());
    }
}

Note that for testing purposes, code has also been added to the method to enable developer mode.

Next, some code needs to be added to apply the parameter values to the user interface. For the purposes of this example, a method named applyConfig() will be added and called from within the onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_remote_config);

    fbRemoteConfig = FirebaseRemoteConfig.getInstance();
    fbRemoteConfig.setDefaults(R.xml.remote_config_params);
.
.
    applyConfig();
}

protected void applyConfig() {

    ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.layout);
    TextView textView = (TextView) findViewById(R.id.welcomeText);

    String bg_color = fbRemoteConfig.getString("main_background_color");
    layout.setBackgroundColor(Color.parseColor(bg_color));
    textView.setTextSize(fbRemoteConfig.getLong("welcome_font_size"));
    textView.setText(fbRemoteConfig.getString("welcome_text"));
}

Compile and run the app and make sure that the in-app parameters are being used to set the background color, text and font size. Assuming the code is working, the next step is to add server-side parameters within the Firebase console.

Adding the Server-side Parameters

Open a browser window, navigate to the Firebase console and select the Firebase Example project. Once the project has loaded, click on the Remote Config option in the navigation panel followed by the Add your first parameter button:


Remote config add first param.png

Figure 37‑5


The first parameter to be added is the welcome text. Within the new parameter dialog (shown in Figure 37‑6), enter welcome_text into the Parameter key field and Welcome to Remote Config into the Default value field before clicking on the Add Parameter button.


Remote config welcome param.png

Figure 37‑6


Repeat this step to add the main_background_color and welcome_font_size parameters set to #f4419d and 35 respectively. On completion of these steps the list of parameters within the console should match that shown in Figure 37‑7:


Remote config params added.png

Figure 37‑7


Having verified that the entries are correct, click on the Publish Changes button to make the configuration changes available to the app.

Fetching and Activating the Remote Parameters

Now that parameters have been added within the console, the app needs to be modified to fetch and activate the changes. Later in this chapter we will look at fetching and activating parameters at app startup. For now though, the callback method on the Update Config button will be used to demonstrate instantly applying configuration changes.

Edit the RemoteConfigActivity.java file and add the updateConfig() callback method as follows:

public void updateConfig(View view) {
    fbRemoteConfig.fetch(0).addOnCompleteListener(this, 
			new OnCompleteListener<Void>() {

        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                fbRemoteConfig.activateFetched();
                applyConfig();
            } else {
               // Fetch failed
            }
        }
    });
} 

The above code calls the fetch() method of the FirebaseRemoteConfig instance with a cache timeout value of 0. A listener is also added which activates the fetched parameters and calls the applyConfig() method so that the changes are immediately visible within the user interface.

Run the app once again, click on the Update Config button and confirm that the changes configured in the console are reflected in the user interface. If any of the changes fail to take effect, check that the parameter keys declared in the Firebase console match those in the in-app parameter resource file. Also add some logging output within the completion listener callback to verify that the fetch operation completes successfully.

Handling Changes at Startup

As outlined in the previous chapter, a recommended strategy for dealing with Remote Config changes is to fetch changes while the app is running and then activate them on the next app launch. To implement this behavior, edit the onCreate() method to first activate any parameters that may have been fetched during the previous session and then perform a new fetch ready for the next time the app is started by the user:

.
.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_remote_config);

    fbRemoteConfig = FirebaseRemoteConfig.getInstance();
    fbRemoteConfig.setDefaults(R.xml.remote_config_params);

    fbRemoteConfig.activateFetched();
    applyConfig();
    fbRemoteConfig.fetch(0);
}
.
.

Note that a completion listener is not added to the fetch() method call this time. This is intentional since no action needs to be taken yet after the fetch operation completes. By design, the updated configuration will not be activated until the next time the app starts up.

To test this behavior perform the following steps:

1. Change the values assigned to the parameter keys in the Firebase console.

2. Run the app and note that, while the changes are fetched in the background they are not activated and visible in the user interface.

3. Stop and restart the app. Note that the cached changes are now activated and visible.

Creating a Conditional Parameter Change

As a final step, a simple condition rule will be added for the background color parameter. Within the Remote Config Firebase console screen, edit the main_background_color parameter and click on the Add value for condition menu as highlighted in Figure 37‑8:


Remote config add value condition.png

Figure 37‑8


From the condition menu, select the Define new condition option. Within the new condition dialog (Figure 37‑9) name the condition My Country, select the Device region/country option and then choose the country in which you are currently residing from the Select countries menu:


Remote config define new condition.png

Figure 37‑9


Click on the Create Condition button to return to the parameter editing dialog. An entry will now be shown for the My Country condition with a field ready to accept a new color settings for all users in your country. Enter a new color setting into this field:


Remote config country color.png

Figure 37‑10


Note that the previous color value is now listed as the default and will be used in all countries except the one specified in the condition.

Click on the Publish Changes button before returning to the running app and clicking on the Update Config button at which point the background color should change indicating the condition is working.

Summary

This chapter has provided a tutorial designed to demonstrate the key features of Firebase Remote Config. This has included the addition of Remote Config support to an Android Studio project, accessing the FirebaseRemoteConfig object and the implementation of in-app parameters using a resource file. The chapter then covered the creation of server-side parameters using the Firebase console and the fetching and activating of those parameters. Finally, a condition was used to target a specific parameter change based on geographical location.




PreviousTable of ContentsNext
Firebase Remote ConfigFirebase Analytics