activity完全退出程序

activity完全退出程序用system.exit(0)有些情况并不能实现,而且有时需要销毁部分activity,只保留一个或一部分activity时就难以实现,所以我们应该把所有activity加入一个集合里面,在对应的地方做相关操作。要实现这个功能最好处理的方法应该继承Application ,因为此类是唯一的,一个程序只有一个Application ,也是程序的入口。


废话少讲,添上代码如下:


public class BaseApplication extends Application {


public List activityList = new LinkedList();


@Override
public void onCreate() {
// TODO Auto-generated method stub

super.onCreate();

}

/**
*  添加Activity到容器中
* @param activity
*/
@SuppressWarnings("unchecked")
public synchronized void addActivity(Activity activity) {
for (int i = 0; i if (((Activity)activityList.get(i)).getLocalClassName().equals(activity.getLocalClassName())) {
activityList.remove(i);
break;
}
}
activityList.add(activity);
}


/**
* activity被销毁时,从activityList中移除
* @param activity
*/
public synchronized void removeActivity(Activity activity){
if (activityList.size()!=0&&activity!=null) {

activityList.remove(activity);
if (!activity.isFinishing()) {
activity.finish();
}
}
}

/**
* 除activityString(如cn.com.MainActivity包名)外的activity都finish
*/
public synchronized void removeActivityUnThisOther(String activityString){
if (activityList.size()!=0) {
Activity activity=null;
@SuppressWarnings("unchecked")
Iteratoriterator=activityList.iterator();
while(iterator.hasNext()){
activity=iterator.next();
if (!activity.toString().contains(activityString)) {
if (!activity.isFinishing()) {
activity.finish();
iterator.remove();
}
}

}
}
}

/**
*  遍历所有Activity并finish
*/
@SuppressWarnings("unchecked")
public synchronized void exit() {
if (activityList.size()!=0) {
Activity activity=null;
Iteratoriterator=activityList.iterator();
while(iterator.hasNext()){
activity=iterator.next();
if (!activity.isFinishing()) {
activity.finish();
iterator.remove();
}
}
}
}
}

你可能感兴趣的:(activity)