technical background
In development, we often encounter such a requirement: Home page--" input account page--" input password page--" login page. When we go to the login page and log in, we will come to the home page. At this time, When we press the back button, we don't want to be transferred to the password or account page. At this time, we need a technique --- delete a specific activity at a specific time. cut to the chase, post the picture.
Technical Principle
Hand write a static Activity management pool by yourself, manage the started Activity, and delete it as you want.
Code combing
Step 1: Encapsulate a CatchActivity class
package com.example.treetest.utils;
import android.app.Activity;
import java.util.ArrayList;
import java.util.List;
public class CatchActivity {
//设置一个用来装 已开启 activity 容器
public static List<Activity> activityList = new ArrayList<>();
//判断容器中是否已存在改 activity,不存在则添加
public static void addActivity(Activity activity){
if (!activityList.contains(activity)){
activityList.add(activity);
}
}
//删除所有 activity
public static void finishAllActivity(){
for (Activity temp: activityList){
temp.finish();
}
}
//删除指定 activity
public static void finishSingleActivity(Activity activity){
if (activity != null){
if (activityList.contains(activity)){
activityList.remove(activity);
}
activity.finish();
}
}
//删除指定activity 通过类名
public static void finishSingleActivityByClass(Class<?> cls){
Activity tempActivity = null;
for (Activity temp : activityList){
if (temp.getClass().equals(cls)){
tempActivity = temp;
}
}
finishSingleActivity(tempActivity);
}
}
Step 2: Call in onCreate() in the Activity that needs to be managed
//往 Activity静态管理池中添加
if(!CatchActivity.activityList.contains(this)){
CatchActivity.addActivity(this);
}
Step 3: Select a "good day" to delete the specified Acitivity
//删除 静态activity管理池
CatchActivity.finishSingleActivityByClass(TestActivity.class);
CatchActivity.finishSingleActivityByClass(TestTireInfoActivity.class);
CatchActivity.finishSingleActivityByClass(ShowDataActivity.class);
to sum up
At this point, you have completely controlled the Activity.
Note: try not to use finishAllActivity() because although the Activity has finished(), there are still corresponding Activities in the activityList, use it with caution! ! ! You can use it, just optimize the code yourself, I won't explain it here! ! !
Just pretend you can’t see it: you can loop without advanced syntax in finishAllActivity(), just use the loop with i variables, stop here.