Activity的回收

Activity的回收与操作超时的处理

1、Activity的回收 
针对多个activity退出的处理

关键代码: 
1、新建活动管理类:

public class ActivityCollector {
    private static List<Activity> activityList = new ArrayList<Activity>();
    public static void addActivity(Activity activity){
        activityList.add(activity);
    }
    public static void removeActivity(Activity activity){
        activityList.remove(activity);
    }

    public static void finishAllButLast(){
        Activity activity = activityList.get(activityList.size()-1);
        removeActivity(activity);

        for (Activity activityItem: activityList){
            if (!activityItem.isFinishing()){
                activityItem.finish();
            }
        }

        activityList.clear();
        activityList.add(activity);
    }

  //退出所有activity
    public static void finishAll(){
        for (Activity activity: activityList){
            if (!activity.isFinishing()){
                activity.finish();
            }
        }
        activityList.clear();
    }
}

 

 

2、创建基类BaseActivity,并使所有的activity继承自该基类 。在创建时,添加到活动管理器,销毁时,从活动管理器中移除。

public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}

如果需要销毁所有activity,只需调用finishAll()即可

posted @ 2016-04-15 16:03  红尘Dream  阅读(210)  评论(0编辑  收藏  举报