当Activity创建的时候把当前的Activity对象存放起来,等等退出的时候,关闭所有的Activity,为此,写了一个MyApplication类,用于存放所有的Activity,代码如下:
public class MyApplication extends Application {
private List<Activity> activityList=new ArrayList<Activity>();
private static MyApplication instance;
private MyApplication(){
}
//单例模式中获取唯一的MyApplication实例
public static MyApplication getInstance(){
if (null==instance) {
instance=new MyApplication();
}
return instance;
}
//添加Activity到容器中
public void addActivity(Activity activitiy){
activityList.add(activitiy);
}
//遍历所有的Activity并finish
public void exit(){
for(Activity activity:activityList){
activity.finish();
}
System.exit(0);
}
}
使用方法:
在Activity的onCreate方法里面加上:
MyApplication.getInstance().addActivity(this);
退出时调用:MyApplication.getInstance().exit();