Firebase

Firebase Remote Config Android

Welcome Guys, In this post I will explain what is Firebase Remote Config Android? How does Firebase Remote Config work in Android? At the end of this tutorial, We will create the Firebase Remote Config Android Sample application.

Suppose it’s any festival such as Christmas and you want to change a theme based on your festival for all the users. The simplest way to upload a new build on play store with a new theme, but it’s not guaranty that all your users will download the update. Also uploading a new build just for theme change would be an unnecessary effort. For one time it doable but if you considering to do all the festivals. In these scenarios, we will use Firebase Remote Config.

What is Firebase Remote Config?

Firebase Remote Config is cloud service. It changes the behavior and appearance of your app without publishing an app update on play store for all active users. Basically, Remote Config allows you to maintain parameters on the cloud, based on these parameters we control the behavior and appearance of your app.

In the festival scenario, we can define parameters with the text, color, images for a theme which can be fetched using Remote Config REST API from your app.

How does Firebase Remote Config work?

In Remote Config, We create in-app default values that control the behavior and appearance (such as text, color, and image, etc. ) in the app. Later on, with the help of Firebase Remote Config, we fetch parameters from the firebase remote config and override the default value.

Basically, Remote Config has three different configs as explained below
  • Default Config – In this config default values defined in your app, If no matching key found on remote config sever than default value is copied the in active config and returned to the client.
  • Fetched Config – Most recent config that fetched from the server but not activated yet. We need to activate these configs parameters, then all value copied in active Config
  • Active Config – It directly accessible from your app. It contains values either default and fetched.
firebase remote config android example
Remote Config Architecture
Let’s see below diagram
firebase remote config fetch android
Remote Config Data Flow

Now the question is how does the app decide what value to be used. Let’s understand this via the below diagram.

android firebase remote config cache
Parameter Decision Flow

The above diagram is self-explanatory, So the default cache value is 12 hours. Firebase Remote Config has some Policies and limits.

Step of Implementation

  • Add Remote Config dependency in app/gradle file
  • Setup Project Firebase Assistant
  • Add the parameters in Firebase Console.
  • Implement remote configuration in your app
  • Add logic to fetch, activate, and get parameter values
  • Test your logic

1. Project Setup and Add Dependencies

Let’s open the Android Studio and create a new project with the default template. We have to add two dependencies one project level and app level

Project Level Dependency

Open project build.gradle

  // Project Level Google Services dependency
   classpath 'com.google.gms:google-services:4.3.0'
App Level Dependency

Now navigate app level build.gradle file and add below dependency. Here I’m using version 18.0.0 is the latest version at the time this post. You can use a newer version.

implementation 'com.google.firebase:firebase-config:18.0.0'
On top add this line
apply plugin: 'com.google.gms.google-services'

2. Designing the Sample Layout

Let’s open the activity_main.xml and paste below code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >
  <RelativeLayout
      android:id="@+id/relativeLayout"
      android:layout_width="match_parent"
      android:layout_height="160dp"
      android:background="#00bfa5"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      >
    <Button
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="#FFF"
        android:fontFamily="@font/raleway"
        android:paddingBottom="4dp"
        android:paddingLeft="32dp"
        android:paddingRight="32dp"
        android:paddingTop="4dp"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp"
        tools:text="Android"
        />

  </RelativeLayout>
  <TextView
      android:id="@+id/tvDescription"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_marginBottom="8dp"
      android:layout_marginEnd="16dp"
      android:layout_marginLeft="16dp"
      android:layout_marginRight="16dp"
      android:layout_marginStart="16dp"
      android:layout_marginTop="8dp"
      android:fontFamily="@font/raleway"
      android:gravity="center"
      android:textColor="#161616"
      android:textSize="25sp"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHorizontal_bias="0.0"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/relativeLayout"
      app:layout_constraintVertical_bias="0.4"
      tools:text="How to become a better Android Developer"
      />
  <Button
      android:id="@+id/btnMore"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginBottom="8dp"
      android:layout_marginEnd="8dp"
      android:layout_marginLeft="8dp"
      android:layout_marginRight="8dp"
      android:layout_marginStart="8dp"
      android:layout_marginTop="8dp"
      android:background="@color/colorAccent"
      android:fontFamily="@font/raleway"
      android:paddingLeft="16dp"
      android:paddingRight="16dp"
      android:textAllCaps="false"
      android:textColor="#fff"
      android:textStyle="bold"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/tvDescription"
      tools:text="Read More"
      />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Go to Firebase Console and create a project

The simplest way is using Firebase Assistant (Tool Menu => Firebase) just click on the text: “Set Up Remote Config” and the above-mentioned library will be automatically added

firebase assistant setup

5. Get Firebase Config instance.

// Get Firebase Remote Config instance.
firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

6. Create a Remote Config Setting

// Create a Remote Config Setting to enable developer mode, which you can use to increase
    // the number of fetches available per hour during development. Also use Remote Config
    // Setting to set the minimum fetch interval.
    FirebaseRemoteConfigSettings.Builder configBuilder = new FirebaseRemoteConfigSettings.Builder();

    // Sets the minimum interval between successive fetch calls.
    /**
     * For developer mode I'm setting 0 (zero) second
     * The default mode is 12 Hours. So for production mode it will be 12 hours
     */
    if (BuildConfig.DEBUG) {
      long cacheInterval = 0;
      configBuilder.setMinimumFetchIntervalInSeconds(cacheInterval);
    }
    // finally build config settings and sets to Remote Config
    firebaseRemoteConfig.setConfigSettingsAsync(configBuilder.build());

7. Defining Default Values

Navigate res folder and create a new folder named xml. Inside the XML folder create a resource file names remote_config_defaults. Set default Remote Config parameter values. An app uses the in-app default values, and when you need to adjust those defaults, you set an updated value for only the values you want to change in the Firebase Console.

<?xml version="1.0" encoding="utf-8"?>
<!-- START xml_defaults -->
<defaultsMap>
  <entry>
    <key>title</key>
    <value>Android</value>
  </entry>
  <entry>
    <key>description</key>
    <value>How to become a better Android Developer</value>
  </entry>

  <entry>
    <key>more_info</key>
    <value>Read More</value>
  </entry>
</defaultsMap>
    <!-- END xml_defaults -->

8. Set Default Values

Set default Remote Config parameter values on Remote Config Instance

   //set default values
    firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);

9. Add the parameters in Firebase Console

Go to Firebase Console and we will see two text fields “Parameter key” and “Default value” which we have to enter key and value click on “PUBLISH “to save our changes.

Firebase recently added JSON value like this
remote config android tutorial

10. Add logic to fetch, activate, and get parameter values

 private void fetchRemoteTitle() {

    // set text from remote
    textViewTitle.setText(firebaseRemoteConfig.getString(TITLE_KEY));
    textViewDescription.setText(firebaseRemoteConfig.getString(DESCRIPTION_KEY));
    buttonMoreInfo.setText(firebaseRemoteConfig.getString(MORE_INFO_KEY));

    // [START fetch_config_with_callback]
    // override default value from Remote Config
    firebaseRemoteConfig.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();
            }
          }
        });
    // [END fetch_config_with_callback]
  }

The full source code looks like

package com.androidwave.remoteconfig;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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 MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";

  TextView textViewTitle, textViewDescription;
  Button buttonMoreInfo;

  // Remote Config keys
  private static final String TITLE_KEY = "title";
  private static final String DESCRIPTION_KEY = "description";
  private static final String MORE_INFO_KEY = "more_info";

  // Firebase Remote Config
  private FirebaseRemoteConfig firebaseRemoteConfig;

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

    // init view
    textViewTitle = findViewById(R.id.tvTitle);
    textViewDescription = findViewById(R.id.tvDescription);
    buttonMoreInfo = findViewById(R.id.btnMore);

    // Get Firebase Remote Config instance.
    firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

    // Create a Remote Config Setting to enable developer mode,
    FirebaseRemoteConfigSettings.Builder configBuilder = new FirebaseRemoteConfigSettings.Builder();

    // Sets the minimum interval between successive fetch calls.
    /**
     * For developer mode I'm setting 0 (zero) second
     * The default mode is 12 Hours. So for production mode it will be 12 hours
     */
    if (BuildConfig.DEBUG) {
      long cacheInterval = 0;
      configBuilder.setMinimumFetchIntervalInSeconds(cacheInterval);
    }
    // finally build config settings and sets to Remote Config
    firebaseRemoteConfig.setConfigSettingsAsync(configBuilder.build());

    /**
     *  Set default Remote Config parameter values. An app uses the in-app default values, and
     * when you need to adjust those defaults, you set an updated value for only the values you
     * want to change in the Firebase console
     */
    //set default values
    firebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
    fetchRemoteTitle();
  }

  private void fetchRemoteTitle() {

    // set text from remote
    textViewTitle.setText(firebaseRemoteConfig.getString(TITLE_KEY));
    textViewDescription.setText(firebaseRemoteConfig.getString(DESCRIPTION_KEY));
    buttonMoreInfo.setText(firebaseRemoteConfig.getString(MORE_INFO_KEY));

    // [START fetch_config_with_callback]
    // override default value from Remote Config
    firebaseRemoteConfig.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();
            }
          }
        });
    // [END fetch_config_with_callback]
  }
}

Now, run your app and go to firebase console update some values in the Remote Config and again restart the app. You will see the changes. In this Firebase Remote Config Sample app everything’s working fine. You can download full source code of firebase remote config android tutorial.

Limits and Policies

Firebase Remote Config has some policies and limits. Before using it please look at once

Policies

  • If your update requires user authorization then you should avoid using the Remote Config to update the app.
  • confidential data of your app should not store  in the Remote Config

Limits

  • Max limit of param is 2000
  • You can maximum 300 versions of your Remote Config and Firebase will keep those maximum time period of 90 days.

Conclusion

So, In this post we learned about Firebase Remote Config, We looked how to set remote parameter, etc. At last, we also saw one implementation of with a sample app. It is very useful when you have some minor update in your app, without publishing app on play store. You can take reference from the official website of Remote Config. I hope you enjoyed this article.

Leave a Reply

2000