如何在Android中清除返回棧?


簡介

在 Android 應用程式中,我們經常需要顯示許多不同型別的 Activity。這些 Activity 用於執行不同的任務。當我們在 Activity 之間導航時,我們之前導航的 Activity 會保留在棧中,這會佔用系統記憶體並可能降低應用程式的效能。為了防止這種情況,我們必須清除 Android 應用程式的 Activity 歷史棧。在本文中,我們將瞭解如何在 Android 中清除返回棧。

實現

我們將建立一個簡單的應用程式,其中我們將建立兩個 Activity。當用戶從一個 Activity 導航到另一個 Activity 時,我們將清除 Activity 的返回棧,以便當使用者從第二個 Activity 按返回鍵時,他將退出應用程式,而不是返回到上一個 Activity。

步驟 1:在 Android Studio 中建立新專案

導航到 Android Studio,如下面的螢幕所示。在下面的螢幕中,點選“新建專案”以建立一個新的 Android Studio 專案。

點選“新建專案”後,您將看到下面的螢幕。

在此螢幕中,我們只需選擇“空 Activity”並點選“下一步”。點選“下一步”後,您將看到下面的螢幕。

在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意 - 確保選擇 Java 作為語言。

指定所有詳細資訊後,點選“完成”以建立一個新的 Android Studio 專案。

專案建立完成後,我們將看到兩個開啟的檔案,即 activity_main.xml 和 MainActivity.java 檔案。

步驟 3:使用 activity_main.xml

導航到 activity_main.xml。如果此檔案不可見,要開啟此檔案,在左側窗格中導航到 app > res > layout > activity_main.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- text view for displaying  heading of the application -->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@id/idBtnOpen"
      android:layout_marginStart="10dp"
      android:layout_marginTop="100dp"
      android:layout_marginEnd="10dp"
      android:padding="5dp"
      android:text="How to Clear Back Stack in Android"
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="@color/black"
      android:textSize="18sp"
      android:textStyle="bold" />
  
   <!-- on below line we are creating a button to post the data -->
   <Button
      android:id="@+id/idBtnOpen"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="20dp"
      android:text="Open new activity"
      android:textAllCaps="false" />
</RelativeLayout>

說明 - 在上面的程式碼中,我們建立了一個 Relative Layout 作為根佈局,並在其中建立了一個簡單的 TextView,用於顯示應用程式的標題。在此 TextView 之後,我們建立了一個簡單的 Button。在點選此 Button 時,我們將開啟第二個 Activity。

步驟 4:建立一個新的 Activity

為了顯示第二個 Activity,我們將建立一個新的 Activity。要建立一個新的 Activity,我們必須導航到 app > 右鍵點選它 > 新建 > Activity > 空 Activity,然後將 Activity 名稱指定為 SecondActivity 並點選“完成”以建立一個新的 Activity。現在您的 Activity 將被建立。

步驟 5:使用 MainActivity.java 檔案

導航到 MainActivity.java。如果此檔案不可見,要開啟此檔案,在左側窗格中導航到 app > res > layout > MainActivity.java 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

package com.example.androidjavaapp;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.toolbox.HttpClientStack;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

   // on below line creating a variable for button and edit text.
   private Button openActivityBtn;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line we are initializing variables.
      openActivityBtn = findViewById(R.id.idBtnOpen);

      openActivityBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            
            // on below line we are creating a new intent.
            Intent i = new Intent(MainActivity.this, SecondActivity.class);
            
            // on below line adding a flag for our activity to clear the history stack.
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            
            // on below line calling a method to start the activity
            startActivity(i);
            
            // on below line calling finish to close the current activity.
            finish();
         }
      });

   }
}

說明 - 在上面的程式碼中,我們為 Button 建立了變數。之後,我們可以看到 onCreate 方法。這是 MainActivity.java 檔案中的一個預設方法,用於載入應用程式的 activity_main.xml 檔案。在該 onCreate 方法中,我們使用我們在 activity_main.xml 檔案中指定的 id 初始化 Button 的變數。初始化變數後,我們為 Button 新增一個點選監聽器。在 Button 的點選監聽器中,我們透過 Intent 開啟一個新的 Activity,最後我們呼叫 finish 方法以從歷史棧中刪除當前 Activity 並將新的 Activity 作為 SecondActivity 開啟。

步驟 6:使用 activity_second.xml

導航到 activity_second.xml。如果此檔案不可見,要開啟此檔案,在左側窗格中導航到 app > res > layout > activity_second.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

<?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>

新增上述程式碼後,我們只需點選頂部的綠色圖示即可在移動裝置上執行我們的應用程式。

注意 - 確保您已連線到您的真實裝置或模擬器。

輸出

在我們的應用程式中,當我們點選 Button 開啟一個新的 Activity 時,我們可以看到我們的新 Activity 已開啟,但同時我們已從 Activity 返回棧中清除了當前 Activity。當我們從第二個 Activity 按返回鍵時,我們的應用程式將關閉。這是因為我們已從 Activity 返回棧中刪除了 MainActivity。

結論

在本文中,我們瞭解瞭如何在 Android 中清除返回棧。此外,我們還了解了如何在 Android 應用程式中實現它。

更新於: 2023年3月30日

3K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.