打开一个Activity, 关闭之前所有的Activity.

时间:2021-10-13 23:42:47

方法一 : 

Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);


方法二 :

 public class CacheActivity {

    public static List<Activity> activityList = new LinkedList<Activity>();

    public CacheActivity() {

    }

    /**  * 添加到Activity容器中  */  public static void addActivity(Activity activity) {
        if (!activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    /**  * 便利所有Activigtyfinish  */  public static void finishActivity() {
        for (Activity activity : activityList) {
            activity.finish();
        }
        activityList.clear();
    }

    /**  * 结束指定的Activity  */  public static void finishSingleActivity(Activity activity) {
        if (activity != null) {
            if (activityList.contains(activity)) {
                activityList.remove(activity);
            }
            activity.finish();
            activity = null;
        }
    }

    /**  * 结束指定类名的Activity 在遍历一个列表的时候不能执行删除操作,所有我们先记住要删除的对象,遍历之后才去删除。  */  public static void finishSingleActivityByClass(Class<?> cls) {
        Activity tempActivity = null;
        for (Activity activity : activityList) {
            if (activity.getClass().equals(cls)) {
                tempActivity = activity;
            }
        }

        finishSingleActivity(tempActivity);
    }
}


在每次新打开的Activity的 oncreat() 方法中调用 addActivity () 方法, 关闭所有Activity的时候调用 finishActivity() 即可.