在平时开发中打开过三个activity,分别为:A, B, C,用android设备中的"back"按钮,需要点击三下,才能退出到主界面(即需要三次操作才能销毁掉这三个activity)。那么如何只需要点击一次back就能一次把这三个activity一次销毁掉呢,方法挺简单的,步骤如下:
(1)创建一个ActivityCollector.java,此类用作收集和销毁activity的公共类.
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<Activity>();
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).创建一个BaseActivity.java基类,项目中的所有activity都继承此类.
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ActivityCollector.removeActivity(this);
}
<span style="font-family: Arial, Helvetica, sans-serif;">}</span>
(3)让A, B, C这三个activity分别去继承BaseActivity.java.这样只要activity一起动,或者子activity中重写了onDestroy()方法,子activity就会自动的去收集activity,去销毁某个Activity.
(4).如何在某个地方需要一次销毁所有的activity,只需要调用ActivityCollector.java中的finishAll()方法.
比如在app中的任何一个界面调用loginout方法,就需要用到一次kill多个activity:
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ConstantUtil.LOGINOUT:
ActivityCollector.finishAll();
break;
}
}