Android 一次性关闭多个Activity

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

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

    private static ActivityControl sInstance = null;
    private final List<Activity> 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()。

发布了17 篇原创文章 · 获赞 12 · 访问量 5591
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览