Working with Firebase Remote Config for Android

In this post we will be covering how to use Firebase Remote config for Android application. Follow this tutorial for basic setup to use Firebase related service in your project.

Use Case

Remote config is useful when you want to make some changes in your app but do want to user to download updated apk. The easy solution to this is creating remote config which you can update and it will get updated on devices.

For example you are using a free server to store your data. At some point of time it was closed, so your users will not able to access that data. Here you can make server url as remote config and when current server address changes you just have to push new url in remote config. All of your users will be now pointed to new server url.

 

[su_button url=”https://github.com/androidsrc/FirebaseRemoteConfig” target=”blank” style=”stroked” background=”#51d461″ color=”#ffffff” size=”6″ center=”yes” radius=”0″ icon=”icon: arrow-circle-o-down”]Download Full Source Code[/su_button]

 

[su_youtube url=”https://youtu.be/buSYAa1vqsw”]

 

Lets start coding

In this sample application we will be using 2 parameters as remote config. These parameters will be added to server and then published. When your app starts we will fetch these parameters and this way latest data will be available to the user.

Follow this tutorial for setting up Firebase for android.

Next you have to add a dependency in app level build.gradle . Add highlighted dependency for using Remote config.

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "net.androidsrc.remoteconfig"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    //firebase core
    compile 'com.google.firebase:firebase-core:10.0.1'
    
    compile 'com.google.firebase:firebase-config:10.0.1'
}

For using remote config you have to create a xml file which will contain default values which will be shipped with the device. So no value is fetched from server then these values from xml will be used.

xml/remote_config_defaults.xml

<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
    <entry>
        <key>display_message</key>
        <value>This is hello from old config</value>
    </entry>
    <entry>
        <key>data_url</key>
        <value>http://google.com</value>
    </entry>
</defaultsMap>
MainActivity.java

Here we will create get a instance of FirebaseRemoteConfig and then default are loaded into it using xml file we created earlier. We will call fetchRemoteConfig() which will initialize the fetching process.

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private TextView textViewDataUrl;
    private FirebaseRemoteConfig mFirebaseRemoteConfig;


    private static final String DISPLAY_MESSAGE = "display_message";
    private static final String DATA_URL = "data_url";

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

        //initialize view objects
        textView = (TextView) findViewById(R.id.textView);
        textViewDataUrl = (TextView) findViewById(R.id.textViewDataUrl);

        //firebase initialization
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                .setDeveloperModeEnabled(BuildConfig.DEBUG)
                .build();
        mFirebaseRemoteConfig.setConfigSettings(configSettings);

        //load defaults from xml if not available from cache
        mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);

        fetchRemoteConfig();

    }

    private void fetchRemoteConfig() {
        //display current config data
        displayCurrentData();

        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();
                        }
                        displayCurrentData();
                    }
                });
    }

    //display active data in text view
    private void displayCurrentData() {
        textViewDataUrl.setText(mFirebaseRemoteConfig.getString(DATA_URL));
        textView.setText(mFirebaseRemoteConfig.getString(DISPLAY_MESSAGE));
    }
}

Fresh data is displayed when it is successfully fetched from the server.

Please comment for any clarification.

GuRu

Technology enthusiast. Loves to tinker with things. Always trying to create something wonderful using technology. Loves coding for Android, Raspberry pi, Arduino , Opencv and much more.

You may also like...

1 Response

  1. Abhishek EH says:

    Good article. Liked it.

Leave a Reply

Your email address will not be published. Required fields are marked *