Open In App

How to Change Android Activity Remotely in Firebase?

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

As we know if some apps are having maintenance or any kind of issues then after opening the app then the app didn’t open and it just gives that popup only. This feature is provided by Firebase remote config we can trigger any activity if the user opens the app. To know more about Firebase remote config check this out: How to Use Remote Config Console in Firebase. A sample video is given below to get an idea about what we are going to do in this article.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect Your project to Firebase first create a Firebase project

First, in the Android studio, Top Click on Tools > Firebase.
aa1.jpgThen lots of options will be displayed on the left side then click on remote config and click on Set up Firebase Remote Config after that.
aa2.jpgNow Connect Your app to Firebase and add all the dependencies of Firebase Remote Config by Clicking on Add Remote Config To Your App.

aa3.jpg

Step 3: Now Go To Your Project Dashboard of Firebase Console After successfully connecting your Android app to Firebase and Click on Build and From Drop Down Select Remote Config.

aa4.jpg

After Selecting Remote Config Click on Remote Config and Click on Create Configuration, After that add the Parameter Name that will be used while fetching the remote config and also for the default value and Set Data Type As a String and in Default Value add your package name with the activity name like that:
aa5.jpg

Step 4: We have changed the splash Screen To One New Activity that is SplashScreen and moved the intent filter to that activity so that when the user opens the app then that activity will be displayed to do that you can edit the AndroidMainfest.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools">
  
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.GFGAPP"
        tools:targetApi="31">
        <activity
            android:name=".SplashScreen"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity2"
            android:exported="false" />
        <activity
            android:name=".MainActivity"
            android:exported="true">
        </activity>
    </application>
  
</manifest>


Step 5: Now Create one Android Resource Directory with Directory Name as XML and Resource Type also as XML, if it is present by default then don’t create that and just create one layout resource layout that will be used when we’ll enable the use-in app default in the remote config then automatically that activity will be opened that is specified here as by default value, so the file name is defualt_config.xml.

XML




<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
    <entry>
        <!-- Key Is Your Parameter Name that you created in Remote Config-->
        <key>activityChange</key>
        <!-- Value will be Your Default Activity-->
        <value>com.example.gfgapp.MainActivity</value>
    </entry>
</defaultsMap>


Step 6: We have created one more activity that is activity.main2.xml and added one text view just for showing Maintenace is Going on when the app opens after the splash screen and a similar layout for the activity.main2.xml file.

Step 7: Now in Java file we have to fetch the remote config based on the parameter name that we specified and also add if we change the remote config value to in-app default and also use network callback if suddenly the internet stops working when the splash screen opens then auto automatically on that screen only it’ll again start fetching the remote config.

activity_splash_screen.xml:

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".SplashScreen">
  
    <TextView
        android:id="@+id/appname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_marginTop="616dp"
        android:text="Geeks For Geeks"
        android:textColor="#F5F5"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>


SplashScreen.java:

Java




package com.example.gfgapp;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
  
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;
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;
  
@SuppressLint("CustomSplashScreen")
public class SplashScreen extends AppCompatActivity {
  
    private TextView appname;
  
    private FirebaseRemoteConfig firebaseRemoteConfig;
    private ProgressBar progressBar;
    private boolean isFetchingEnabled = true;
  
    private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            if (isFetchingEnabled) {
                fetchRemoteConfig();
            }
        }
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        progressBar = findViewById(R.id.progressBar);
  
        firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                .setMinimumFetchIntervalInSeconds(0)
                .build();
        firebaseRemoteConfig.setConfigSettingsAsync(configSettings);
            
          // Make Sure You add your default value that you created 
        firebaseRemoteConfig.setDefaultsAsync(R.xml.default_config);
  
        appname = findViewById(R.id.appname);
  
        // Animating the Textview that is ("Geeks For Geeks")
        appname.animate().translationY(-1400).setDuration(1500).setStartDelay(0);
  
        firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
            @Override
            public void onComplete(@NonNull Task<Boolean> task) {
                if (task.isSuccessful()) {
                    // Fetching and activating successful then retrieve
                      // the main activity name from the remote config
                    String mainActivityName = firebaseRemoteConfig.getString("activityChange");
                        
                    updateActivityName(mainActivityName);
                } else {
                    // Fetching and activating failed then showing 
                      // error and starting monitoring network changes
                    showInternetConnectionError();
                    startMonitoringNetworkChanges();
                }
            }
        });
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        startMonitoringNetworkChanges();
    }
  
    @Override
    protected void onPause() {
        super.onPause();
        stopMonitoringNetworkChanges();
    }
  
    private void updateActivityName(String mainActivityName) {
        launchMainActivity(mainActivityName);
    }
  
    private void launchMainActivity(String mainActivityName) {
        try {
            // Dynamically launching the main activity based
              // on the retrieved name from remote config
            Class<?> mainActivityClass = Class.forName(mainActivityName);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(getApplicationContext(), mainActivityClass);
                    startActivity(intent);
                    progressBar.setVisibility(View.GONE);
                }
            }, 2000);
        } catch (ClassNotFoundException e) {
            // Showing the  error toast if the
              // main activity class is not found
            showErrorToast();
            e.printStackTrace();
            progressBar.setVisibility(View.GONE);
        }
    }
  
    private void fetchRemoteConfig() {
        // Fetching and activating the remote config
        firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
            @Override
            public void onComplete(@NonNull Task<Boolean> task) {
                progressBar.setVisibility(View.VISIBLE);
                if (task.isSuccessful()) {
                    // Fetching and activating successful then retrieve the
                      // main activity name from the remote config
                    String mainActivityName = firebaseRemoteConfig.getString("activityChange");
                    updateActivityName(mainActivityName);
                } else {
                    // Fetching and activating 
                      // failed then show error
                    showInternetConnectionError();
                }
            }
        });
    }
  
    private void startMonitoringNetworkChanges() {
        // Register network callback to monitor network changes
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest networkRequest = new NetworkRequest.Builder().build();
        cm.registerNetworkCallback(networkRequest, networkCallback);
    }
  
    private void stopMonitoringNetworkChanges() {
        // Unregister network callback to stop monitoring network changes
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        cm.unregisterNetworkCallback(networkCallback);
    }
  
    private void showInternetConnectionError() {
        // Toast message for internet connection error
        Toast.makeText(this, "Please check your internet connection", Toast.LENGTH_LONG).show();
    }
  
    private void showErrorToast() {
        // Error toast message
        Toast.makeText(this, "Error Occurred", Toast.LENGTH_SHORT).show();
    }
}


Note: To change the Remote Config Just Click on The edit option that is visible on the left side and after editing make sure to publish the changes.

Output:

If Default Value is set to “com.example.gfgapp.MainActivity2”, after a few seconds if Default Value is Set To Use-In App Default.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads