android实现退出时关闭所有activity

来自郭霖《第一行代码》


1、新建ActivityCollector类,代码如下:

public static List activities = new ArrayList();
public static void addActivity(Activity activity) {
    activities.add(activity);
}
public static void removeActivity(Activity activity) {
    activities.remove(activity);
}
public static void finishAll() {
    for (Activity activity : activities) {
        if (!activity.isFinishing()) {
            activity.finish();
        }
    }
}

2、在每个activity中

重写onCreate方法,在super.onCreate(savedInstanceState);后调用ActivityCollector.addActivity(this);

重写onDestroy方法,在super.onDestroy();后调用ActivityCollector.removeActivity(this);


3、在退出程序的地方,调用:ActivityCollector.finishAll();


你可能感兴趣的:(Android)