Android Firebase Remote Config Example

This tutorial explains how to add Firebase remote config to your Android app. Before going into the working details, here is an overview of Firebase Remote Config.

What is Firebase Remote Config?

android firebase

Android Firebase Remote Config is a simple key value store that lives in the cloud. As it lives in the cloud it means you are able to deploy changes that your app can read in a matter of minutes. It changes the behavior and appearance of your app without publishing an update of your app.

As it is a cloud service so there is no need to download an app update. Firebase Remote Config allows you to change the look-and-feel of your app, gradually roll out features, run A/B tests, and deliver customized content to certain users, all from the cloud without needing to publish a new version of your app.

How Firebase Remote Config works?

Firebase Remote Config works by allowing us to define in-app parameters that can be overridden from within the Firebase console. These parameters can then be activated for all or for a defined set of users.

If you want to change few lines of text in your app, instead of going through whole build and publishing process which takes days, you can do it on your fingertips using Firebase.

Through the Firebase console you can change your text and press update. The next time when your user fire up the app, remote control config will grab the latest values and update your app.

Remote Config Audience segmentation feature allows you to deliver different configuration of your app to different groups of users simultaneously. It can also deliver different configuration sets to your user based on different factors from device type like iOS or Android, or based on locale.

Let’s get started

Here is the step by step guide of how to use Firebase Remote Config in your Android app. Follow these steps.

Adding Firebase to your Android App

Follow these steps to add Firebase to your Android App.

Prerequisites

⦁ Latest version of Android Studio 1.5 or higher

⦁ Google Play Services SDK

⦁ Android device with version 2.3 or higher

⦁ Google Play Services with 10.0.1 or higher

Adding Firebase to your app is very easy and simple. Go to Firebase Console and create a new project on Firebase console.

⦁ Click on New Project to start a new project.

⦁ Enter Project Name as “Hello World” and click on Create New Project.

⦁ You will see the following screen

⦁ Click on Add Firebase to your Android app

⦁ Enter Package Name of your app as com.helloworld.android

⦁ App Nickname and Debug signing certificate is optional

⦁ Click on Add App button

⦁ Download a config file google-services.json

⦁ Place this file into your Android app module root directory

⦁ Click Continue

⦁ Open your build.gradle file to modify it

⦁ Project-level build.gradle

buildscript
buildscript {
 dependencies {
   // Add this line
    classpath 'com.google.gms:google-services:3.0.0'
  }
}

⦁ Go to Project/ App-module/build.gradle and add the following lines of code

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

⦁ This is how it looks

Apply plugin: ‘com.android.application’
Android {
//....
}
Dependencies {
//....
Compile ‘com.google.firebase:firebase-crash:9.4.0’
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

⦁ Finally press Sync Now in bar that appears in IDE

⦁ If you want to add an existing project in Firebase Click on Import Google Project and follow remaining steps

Getting remote config singleton object

⦁ Go to your app in Android Studio

⦁ Go to project root folder

⦁ Open MainActivity.java

⦁ Get remote config singleton object by usingFirebaseRemoteConfig.getInstance()method as shown here in sample code.

package com.google.samples.quickstart.config;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


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";


    // Remote Config keys
    private static final String LOADING_PHRASE_CONFIG_KEY = "loading_phrase";
    private static final String WELCOME_MESSAGE_KEY = "welcome_message";
    private static final String WELCOME_MESSAGE_CAPS_KEY = "welcome_message_caps";


    private FirebaseRemoteConfig mFirebaseRemoteConfig;
    private TextView mWelcomeTextView;


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

        mWelcomeTextView = ( TextView ) findViewById ( R.id.welcomeTextView );

        Button fetchButton = ( Button ) findViewById( R.id.fetchButton );
        fetchButton.setOnClickListener ( new View.OnClickListener ( ) {
            @Override
            public void onClick ( View v ) {
                fetchWelcome( );
            }
        } );


        // Get Remote Config instance.
        // [START get_remote_config_instance]
        mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance ( );
        // [END get_remote_config_instance]


        // Create Remote Config Setting to enable developer mode.
        // Fetching configs from the server is normally limited to 5 requests per hour.
        // Enabling developer mode allows many more requests to be made per hour, so developers
        // can test different config values during development.
        // [START enable_dev_mode]
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder( )
                .setDeveloperModeEnabled ( BuildConfig.DEBUG )
                .build();
        mFirebaseRemoteConfig.setConfigSettings ( configSettings );
        // [END enable_dev_mode]


        // Set default Remote Config values. In general you should have in app defaults for all
        // values that you may configure using Remote Config later on. The idea is that you
        // use the in app defaults and when you need to adjust those defaults, you set an updated
        // value in the App Manager console. Then the next time you application fetches from the
        // server, the updated value will be used. You can set defaults via an xml file like done
        // here or you can set defaults inline by using one of the other setDefaults methods.S
        // [START set_default_values]
        mFirebaseRemoteConfig.setDefaults ( R.xml.remote_config_defaults );
        // [END set_default_values]


        fetchWelcome( );
    }


    /**
     * Fetch welcome message from server.
     */
    private void fetchWelcome ( ) {
        mWelcomeTextView.setText(mFirebaseRemoteConfig.getString(LOADING_PHRASE_CONFIG_KEY));


        long cacheExpiration = 3600; // 1 hour in seconds.
        // If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
        // the server.
        if (mFirebaseRemoteConfig.getInfo( ).getConfigSettings( ).isDeveloperModeEnabled( )) {
            cacheExpiration = 0;
        }


        // [START fetch_config_with_callback]
        // cacheExpirationSeconds is set to cacheExpiration here, indicating that any previously
        // fetched and cached config would be considered expired because it would have been fetched
        // more than cacheExpiration seconds ago. Thus the next fetch would go to the server unless
        // throttling is in progress. The default expiration duration is 43200 (12 hours).
        mFirebaseRemoteConfig.fetch ( cacheExpiration )
                .addOnCompleteListener ( this, new OnCompleteListener <Void>( ) {
                    @Override
                    public void onComplete(@NonNull Task <Void> task ) {
                        if ( task.isSuccessful ( )) {
                            Toast.makeText ( MainActivity.this, "Fetch Succeeded",
                                    Toast.LENGTH_SHORT ).show( );


                            // Once the config is successfully fetched it must be activated before newly fetched
                            // values are returned.
                            mFirebaseRemoteConfig.activateFetched ( );
                        } else {
                            Toast.makeText ( MainActivity.this, "Fetch Failed",
                                    Toast.LENGTH_SHORT).show( );
                        }
                        displayWelcomeMessage( );
                    }
                } );
        // [END fetch_config_with_callback]
    }


    /**
     * Display welcome message in all caps if welcome_message_caps is set to true. Otherwise
     * display welcome message as fetched from welcome_message.
     */
     // [START display_welcome_message]
    private void displayWelcomeMessage( ) {
        // [START get_config_values]
        String welcomeMessage = mFirebaseRemoteConfig.getString ( WELCOME_MESSAGE_KEY );
        // [END get_config_values]
        if ( mFirebaseRemoteConfig.getBoolean ( WELCOME_MESSAGE_CAPS_KEY )) {
            mWelcomeTextView.setAllCaps ( true );
        } else {
            mWelcomeTextView.setAllCaps ( false );
        }
        mWelcomeTextView.setText ( welcomeMessage );
    }
    // [END display_welcome_message ]
}

⦁ The basic purpose of singleton object is, it is used to fetch updated parameter values from service and to store in-app default values

XML default file

⦁ Use a Map (An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value) object to define a set of parameter names and default values.

⦁ Or you can use XML resource file stored in your app’s res/xml folder

⦁ The XML defaults file is just a description of the key and the default value of the parameters you wish to configure remotely.

⦁ Go to your app-module’s ../res directory, and create an xml directory. It is within this directory that the file should be placed. Note that the keys have to be the same as you used on the Firebase Console.

⦁ Here is an example code

< ? Xml version = “1.0” encoding = “utf-8”? >
<! -----  start xml defaults ----- >
< defaultsMap > 
< entery > 
< key > signup_prompt </key> 
<value> Hello World, Sign Up please </value> 
</entry> 
<entry> 
<key> color_primary </key> 
<value>  #3F51B5 </value> 
</entry> 
<entry> 
<key> min_passowrd-length </key> 
<value>  8 </value> 
</entry> 
</defaultsMap> 
<! ---- ends xml defaults --- > 

Get Parameter values from the remote config

⦁ Get parameter values from the remote config to use in your app

⦁ Configure in-app parameter values using setDefault()

⦁ Call the following ,methods that match to the data type expected by your app

getString( String key ):get the value corresponding to the specified key, as a string

getByteArray( String key ): get the value corresponding to the specified key, as a byte array

getBoolean( String key ): get the value corresponding to the specified key, as a boolean

getDouble( String key ): get the value corresponding to the specified key, as a double

getLong( String key ):get the value corresponding to the specified key, as a long

⦁ You can fetch and activate values if you set it in remote config, values will be available to your app.

Set parameter values on the server

⦁ An important step is to set parameter value on the server

⦁ Go to your Firebase console

⦁ Open your project app

⦁ Navigate remote config page of your console dashboard It looks like this

Remote config

⦁ Now think what values you want to remotely configure in your app

⦁ List down all your parameters on a note and take a critical examine what you have listed down.

⦁ As it is very easy to decode any parameter keys or values stored in remote config settings of your project so make sure you are not storing any confidential data in remote config parameter values or keys.

⦁ Don’t make any app update that require user Authorization. This can create problem and make your app insecure.

⦁ After complete examine you can add parameters to your app by clicking Add Your First Parameter

⦁ Add Parameter Key ( This is the key you will pass to remote Remote Config SDK ) and set Default value

⦁ Click on Add Parameter

⦁ Again Click on Add Parameter if you want to add more parameters to your app

⦁ When you are done with adding parameters, click on Publish Changes, they will be immediately available to your app and users.

⦁ If you want to discard, click on Discard All

⦁ Similarly you can add conditions to your app (Use conditions to target specific situations, such as staged rollouts and A/B tests, where parameter values should change )

⦁ Go to Add Value For Condition

⦁ Click on Define new Condition

Remote config conditions

⦁ If you want to remove or change your condition, go to Conditions tab. That’s all, this is how simple it is. Now you can fetch values from the service.

To fetch values from the service

⦁ Simply call fetch() method to fetch values from the remote config service. It fetches parameter values for your app. Parameter values may be from the Default Config (local cache), or from the Remote Config Server, depending on how much time has elapsed since parameter values were last fetched from the Remote Config server. This method uses the default cache expiration of 12 hours.

⦁ Call activatefetched() method to make fetched parameter values available to your app. It activates the Fetched Config, so that the fetched key-values take effect. Returns true if there was a Fetched Config, and it was activated. Returns false if no Fetched Config was found, or the Fetched Config was already activated.

Conclusion

The major benefit of remote config is delivering the right experience to right users. With the help of Firebase Remote Config you can quickly and easily update our applications without the need to publish a new build to the app / play store.

For example, we could easily switch out a rebuild of a component in our application for a select set of users based on the conditions that we specify.

This tutorial explains each and every step in easy and understandable words. I hope this tutorial will be helpful to you.

 

OTHER INTERESTING POSTS:

Add a Comment