Android 一次性关闭多个Activity

Android开发中,有时需要一次性关闭多个Activity但不退出应用,这时我们可以通过管理一个ArrayList来实现。具体如下:

public class ActivityControl {
    private static final String TAG = "ActivityControl";

    private static ActivityControl sInstance = null;
    private final List mList = new ArrayList<>();

    public static ActivityControl getInstance() {
        if (sInstance == null) {
            synchronized (ActivityControl.class) {
                if (sInstance == null) {
                    sInstance = new ActivityControl();
                }
            }
        }
        return sInstance;
    }

    public void add(Activity activity) {
        Log.d(TAG, "add:" + activity.toString());
        mList.add(activity);
    }

    public void close(Activity activity) {
        if (mList.contains(activity)) {
            Log.d(TAG, "close:" + activity.toString());
            mList.remove(activity);
            activity.finish();
        }
    }

    public void closeAll() {
        try {
            Log.d(TAG, "mList.size() = " + mList.size());
            for (int i = 0; i < mList.size(); i++) {
                Activity activity = mList.get(i);
                if (activity != null) {
                    Log.d(TAG, "closeAll:" + activity.toString());
                    mList.remove(activity);
                    activity.finish();
                    i--; //因为位置发生改变,所以必须修改i的位置,否则会有ConcurrentModificationException
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 启动一个Activity时调用add()方法,关闭时调用close(),一次性关闭所有Activity时调用closeAll()。

你可能感兴趣的:(Android)