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

方法一:

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 activityList = new LinkedList();

    public CacheActivity() {

    }

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

    /**
     * 便利所有Activigty并finish
     */
    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() 即可

转自Crazy_弑神风的博客:http://blog.csdn.net/liangcai_csdn/article/details/71104724

你可能感兴趣的:(android-studio)