Force Update of Firebase Remote Config on Android (Tutorial)

Do you want to compel users to upgrade your app using Firebase Remote Config?

Firebase Remote Config

Then you'll discover something extraordinary.

Forcing your girlfriend to get you a PS5 for your birthday isn't exactly magical.

What is Firebase?

Firebase is a smartphone and web app development platform launched in 2011 by Firebase, Inc. It was later purchased by Google in 2014.

What is Firebase Remote Config, and How Does it Work?

Firebase Remote Config could be a cloud service that enables you to switch your app's actions ANd look while not forcing users to transfer an update.

You build in-app default values that govern the actions and appearance of your app when you use Remote Config.

Then, for all app users or for parts of your user base, you can use the Firebase console or the Remote Config REST API to override in-app default values. Isn't it cool?

What's the best part?

Your app will search for updates on a regular basis and instal them without degrading results.

Let me give you an example before I start implementing Firebase Remote Config in Android.

Assume you have an app that uses the Instagram API to fetch any user data and display it inside the app.

All is perfect with your app.

You're expanding the user base and receiving a steady stream of positive feedback.

However, one day you receive an email from Instagram informing you that their API has changed and that you should update it as soon as possible.

Okay, you got it; all you need to do now is make a small code update before the deadline.

You open Android Studio, fix the API, create a signed APK, and publish it on Google Play.

You thought it was resolved now, right?

However, one evening, you receive a notification from your Google Play Console App stating that a user has left a negative review stating that your app is broken or completely useless.

The notification gives you the creeps because you've thoroughly checked every aspect of your app, and how could that user say anything like that?

However, when you look into the specifics, you'll notice that the user is still using an outdated version of the app that uses an out-of-date Instagram API.

That's where the issue starts.

You stayed up all night pondering how you could persuade the user to upgrade the app.

The Firebase Remote Config kicks in at this stage.

I'll teach you how to use Firebase Remote Config to compel your users to upgrade the software in this tutorial.

But, as I'll clarify at the end, you can use Firebase Remote Config in a variety of other ways.

How can we compel the user to use Firebase Remote Config to update the app?

We will:
  1. Incorporate Firebase Remote Config into your Android application.
  2. In the Remote config panel, save the current version code of an app.
  3. Get the value from Remote Config and compare it to the current app version code to see if it's higher; if it is, prompt the user to upgrade the app. Aside from that, the app has already been revised.
Okay, let’s start then.

In Android Studio, Create a New Project

  1. To begin, open Android Studio.
  2. Start a new project by clicking the button.
  3. Fill in the application's name. (I accessed the Firebase Remote Configuration Tutorial.)
  4. Enter the company's domain name (androidbull.com)
  5. Enter your current location.
  6. Complete the wizard with everything else and leave the default settings.
My project created with the package name “com.androidbull.firebaseRemoteConfigTutorial”.

I'm going to set up Firebase Project and integrate it into Android Studio before doing some coding.

Install the Firebase SDK on Your Android Device

  1. Firebase Console should now be open.
  2. Develop a new project and call it "Firebase RemoteConfig Tutorials" – it's telling me that I only have one project left, despite the fact that I've already built many.
  3. Check the TOS box and then click "Create Project."
  4. Select “Add Firebase to your Android App” from the drop-down menu.
  5. Enter the package name (I used "com.androidbull.firebaseremoteconfigtutorials" as an example).
  6. Enter the nickname for the app (Remote Config App).
  7. Click Register app – leave SHA-1 blank for now as it isn't needed.
  8. Now, copy the google-service.json file to your project's app directory.
  9. Next should be selected.
  10. As guided, copy and paste the dependencies.
  11. In Android Studio, sync the project.
  12. Next should be selected.
  13. Run your software on an emulator or a real computer so that Firebase can check that everything is in order. This stage can also be skipped, but it is not recommended.
  14. You can go to your Firebase console after you've installed and run your programmed.

Using Firebase Remote Configuration in Android

So, Firebase has been added? After that, add Firebase Remote Config.

Step 1 - Add the Firebase Remote Config dependency to your Android project by pasting the code below into the dependencies section of build.gradle(app).

implementation 'com.google.firebase:firebase-config:16.0.0'

Step 2 - In the Firebase Console, open the Firebase project.

Step 3 - Select Remote Config in the Grow portion of the left window.

Step 4 - You will now be presented with a form where you must enter the Parameter Key and Default Value.

Step 5 - I'll explain what they are in a moment. For now, set Parameter Key to "latest app version" and set the default value to null.

Step 6 - Pick "Define New Condition" from the top-right drop-down menu that says "Add value for Condition."

Step 7 - Enter the condition name (I used "Remote Config App Only") in the new dialogue.

Step 8 - You can choose any color you want.

Step 9 - Pick App from the drop-down menu in Applies if, and then select the same package name on the right side and press Create.

Step 10 - After you've generated the condition, you'll notice another text field labelled "Value for Remote Config App Only." In that area, type 2. To add a parameter, click Add Parameter.

Step 11 - Then press the Publish Changes button.

For Remote Config App Only, what is the parameter key, default value, and value?
  • A parameter could be a key that may be employed in the app to spot that price.
  • The default price is that price which can be served against that specific Parameter Key if no condition is met.
  • And worth for Remote Config App solely is that the worth that may be sent if that condition is consummated.
If we ask for the value of “latest app version” from another app, we will get null. And if we ask it of an app with the package name "com.androidbull.firebaseremoteconfigtutorial," it will return 2 – since there could be several applications in the same Firebase Project. That's why we put that restriction in place.

In Android, getting data from Firebase Remote Config

Let me clarify how Firebase Remote Config works before I start writing code.

We must first obtain the Remote Config Singleton Object.

Then, in-app, set a default parameter value.

To use in your app, get parameter values.

So, let's get started with Android Studio:

Build a FirebaseRemoteConfig instance in MainActivity.java and initialise it as follows:

private FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

Now we'd like to form a HashMap to line defaults to base Remote Config.

private HashMap<String, Object> firebaseDefaultMap;
firebaseDefaultMap = new HashMap<>();

Put the new version code of an app against the main "latest app version" in the default Chart.

String VERSION_CODE_KEY  = "latest_app_version";
firebaseDefaultMap.put(VERSION_CODE_KEY, BuildConfig.VERSION_CODE);

Set Firebase Remote Config Instance as the default HashMap now.

mFirebaseRemoteConfig.setDefaults(firebaseDefaultMap);

Now we must configure the Firebase Remote Config settings to allow developer mode.

mFirebaseRemoteConfig.setConfigSettings(
        new FirebaseRemoteConfigSettings.Builder().setDeveloperModeEnabled(BuildConfig.DEBUG)
            .build());

We must now fetch the data and add a onCompleteListener that will be called once the fetch process is complete.

And inside that, we'll see whether the procedure went smoothly or not. If the fetch function is not efficient, we can either call it again or display an acceptable message.

If the task was completed successfully, use trigger tech() to render the values accessible in the app. Then we use the feature to see if the value from the server is greater than or equal to the current version of the app.

mFirebaseRemoteConfig.fetch().addOnCompleteListener(new OnCompleteListener<Void>() 
{
@Override
public void onComplete(@NonNull Task<Void> task) 
{
    if (task.isSuccessful()) 
{
        mFirebaseRemoteConfig.activateFetched();
        Log.d(TAG, "Fetched value: " + mFirebaseRemoteConfig.getString(VERSION_CODE_KEY));
        //Calling function to examine if refashion is obtainable or not
        checkForUpdate();
      }else
        Toast.makeText(MainActivity.this,"Someting went wrong please try again",Toast.LENGTH_SHORT).show();
    }
});
Log.d(TAG, "Default value: " + mFirebaseRemoteConfig.getString(VERSION_CODE_KEY));
}

We compare the current value to the one we got from the firebase console within the search for update() method. And if the Firebase value is higher, it indicates that a new version is available. Now we must show the Alert Dialog prompting the user to update the app.

private void checkForUpdate() 
{
    int latestAppVersion = (int) mFirebaseRemoteConfig.getDouble(VERSION_CODE_KEY);
    if (latestAppVersion > getCurrentVersionCode()) 
{
      new AlertDialog.Builder(this).setTitle("Please Update the App")
          .setMessage("A new version of this app is available. Please update it").setPositiveButton(
          "OK", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) 
{
              Toast.makeText(MainActivity.this, "Take user to Google Play Store", Toast.LENGTH_SHORT).show();
            }
          }).setCancelable(false).show();
    } else 
{
      Toast.makeText(this,"This app is already upto date", Toast.LENGTH_SHORT).show();
    }
}

My MainActivity.java file's complete code can be found below. In an XML format, I made no changes.

package com.androidbull.firebaseremoteconfigtutorial;

import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException; 
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
import java.util.HashMap;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends AppCompatActivity 
{
 
  private FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
  private HashMap<String, Object> firebaseDefaultMap;
  public static final String VERSION_CODE_KEY = "latest_app_version";
  private static final String TAG = "MainActivity";
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //This is the standard Map.
    firebaseDefaultMap = new HashMap<>();
    //Using the latest version code to set the Default Map Value
    firebaseDefaultMap.put(VERSION_CODE_KEY, getCurrentVersionCode());
 
    //Setting the Firebase Remote Config as the default Map
    mFirebaseRemoteConfig.setDefaults(firebaseDefaultMap);
 
    //To quickly retrieve values, allow Developer Mode.
    mFirebaseRemoteConfig.setConfigSettings(
        new FirebaseRemoteConfigSettings.Builder().setDeveloperModeEnabled(BuildConfig.DEBUG)
            .build());
 
    //Getting the numbers here
    mFirebaseRemoteConfig.fetch().addOnCompleteListener(new OnCompleteListener<Void>() {
      @Override
      public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
          mFirebaseRemoteConfig.activateFetched();
          Log.d(TAG, "Fetched value: " + mFirebaseRemoteConfig.getString(VERSION_CODE_KEY));
          //Checking if a new version is available by calling a feature
          checkForUpdate();
        }else
          Toast.makeText(MainActivity.this,"Someting went wrong please try again",Toast.LENGTH_SHORT).show();
      }
    });
 
    Log.d(TAG, "Default value: " + mFirebaseRemoteConfig.getString(VERSION_CODE_KEY));
  }
 
  private void checkForUpdate() {
    int latestAppVersion = (int) mFirebaseRemoteConfig.getDouble(VERSION_CODE_KEY);
    if (latestAppVersion > getCurrentVersionCode()) {
      new AlertDialog.Builder(this).setTitle("Please Update the App")
          .setMessage("A new version of this app is available. Please update it").setPositiveButton(
          "OK", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
              Toast
                  .makeText(MainActivity.this, "Take user to Google Play Store", Toast.LENGTH_SHORT)
                  .show();
            }
          }).setCancelable(false).show();
    } else {
      Toast.makeText(this,"This app is already upto date", Toast.LENGTH_SHORT).show();
    }
  }
  private int getCurrentVersionCode() {
    try {
      return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
      e.printStackTrace();
    }
    return -1;
  }
}

Now, let's see how the software works. It will automatically verify that the app's current version code matches the one obtained from Firebase Remote Config.

If they are identical, a toast message will appear, indicating that your app is already up to date. Otherwise, the user would be prompted to update the programmed. So, when you upgrade your software, all you have to do is update Firebase Remote Config with the new version code. That is everything there is to it.

I hope you were able to take one thing off from it.

Usage of Firebase Remote Config Policies and Limits

Note the subsequent policies:
  • Don’t use Remote Config to create app updates that ought to need a user’s authorization. this might cause your app to be perceived as fly-by-night.
  • Don’t store confidential knowledge in Remote Config parameter keys or parameter values. it's attainable to rewrite any parameter keys or values hold on within the Remote Config settings for your project.
  • Don’t conceive to circumvent the necessities of your app’s target platform exploitation Remote Config.

Parameter and Condition Limits

You can have up to 2000 parameters and 100 conditions in a Firebase project. Parameter keys can be up to 256 characters long, begin with an underscore or an English letter character (A-Z, a-z), and include numbers. Within a project, the total length of parameter value strings cannot exceed 500,000 characters.

Post a Comment

Previous Post Next Post