How to remove an activity from the history stack in Android ?


Introduction

Many times in android applications we use to display so many different types of activities. This activities are used in android applications for performing the different tasks. When we are navigating from one activity to another activity, the previous activity from which we have navigated remains in the stack, which will take system memory and may degrade the performance of the application. To prevent this we have to clear the activity history stack of an android application. In this article we will take a look on How to remove an activity from the history stack in Android.

Implementation

We will be creating a simple application in which we will be creating two activities. When a user will navigate from one activity to another activity we will be clearing the activity history stack so that when the user presses back from the second activity he will exit from the app instead of going back to the previous activity.

Step 1: Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 3 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Activity 1"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- on below line creating a button to open a new activity-->
   <Button
      android:id="@+id/idBtnOpenSecondActivity"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idTVHeading"
      android:layout_centerHorizontal="true"
      android:layout_margin="20dp"
      android:text="Open Second Activity"
      android:textAllCaps="false" />     
</RelativeLayout>

Explanation − In the above code we are creating a Relative layout as a root layout and inside that we are creating a simple text view in which we are displaying the heading of our application. After this text view we are creating a simple button. Inside the on click of this button we will be opening our second activity.

Step 4 : Creating a new activity.

For displaying a second activity, we will be creating a new activity. For creating a new activity we have to navigate to app>Right click on it>New>Activity>Empty Activity and then specify the activity name as SecondActivity and click on Finish to create a new activity. Now your activity will be created.

Step 5 : Working with MainActivity.java file.

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

   // on below line we are creating variable for button.
   private Button openActivity2Btn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line initializing variable with id.
      openActivity2Btn = findViewById(R.id.idBtnOpenSecondActivity);
      // on below line adding click listener for our button.
      openActivity2Btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line we are opening a new activity using intent
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            // on below line starting a new activity
            startActivity(i);
            // on below line calling a finish method which will clear the current activity from the activity history.
            finish();

         }
      });
   }
}

Explanation − In the above code we are creating variables for our button. After that we can get to see the onCreate method. This is a default method in our MainActivity.java file which is used to load the activity_main.xml file of our application. Inside this onCreate method we are initializing the variable for the button with the id which we have given in our activity_main.xml file. After initializing our variable we are adding a click listener for our button. Inside the click listener for our button we are opening a new activity through intent and lastly we are calling the finish method to remove the current activity from the history stack and open the new activity as SecondActivity.

Step 6 : Working with activity_second.xml.

Navigate to activity_second.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_second.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".SecondActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Welcome to Second Activity"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

</RelativeLayout>

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Inside our application when we click on a button to open a new activity, we can get to see our new activity has opened but at the same time we have cleared the current activity from our activity history stack. When we press back from the second activity our app is getting closed. This is because we have removed the MainActivity from our activity history stack.

Conclusion

In this article we have taken a look on How to remove an activity from the history stack of an android application. This will help us to reduce the memory consumption and improve the performance of an android application.

Updated on: 30-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements