在Application中建立activity中列表,统一管理activity

1.application代码

public class MyApplication extends Application {

    //用于存放我们所有activity的数组
    public static List activities;

    //向集合中添加一个activity
    public static void addActivity(Activity activity){
      if(activities == null){
          //如果集合为空  则初始化
          activities = new ArrayList<>();
      }
        //将activity加入到集合中
        activities.add(activity);
    }

    //结束掉所有的Activity
    public static void finishAll(){
        //循环集合,  将所有的activity finish
        for(Activity activity : activities){
            if(! activity.isFinishing()){
                activity.finish();
            }
        }
    }
    public static void removeActivity(Activity activity){
        //移除已经销毁的Activity
        activities.remove(activity);
    }
}


2.Activity基类代码:


public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //将当前类加入到Activity的集合里
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //将集合里的Activity销毁
        MyApplication.removeActivity(this);
    }
}

你可能感兴趣的:(android知识点)