如题所述
步骤如下:
(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:
[java] view plaincopyprint?
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ConstantUtil.LOGINOUT:
ActivityCollector.finishAll();
break;
}
}
(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:
[java] view plaincopyprint?
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case ConstantUtil.LOGINOUT:
ActivityCollector.finishAll();
break;
}
}
温馨提示:答案为网友推荐,仅供参考