如何在一个app中随时退出所有活动,不用一直按back
新建一个BaseActivity类
- 新建一个BaseActivity类, 继承自AppCompatActivity
- 重写onCreat()
- 所有的activity继承自自BaseActivity
public class BaseActivity extends AppCompatActivity{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("BaseActivity", getClass().getSimpleName()); // 获取活动名称 }
新建ActivityCollector 类作为活动管理器
- 通过一个List来暂存活动
- 提供一个addActivity()方法向List添加一个活动
- 提供一个removeActivity()方法来移除List中活动
- 提供finishAll()方法来销毁所有List中活动
public class ActivityCollector {
public static List<Activity> activities = new ArrayList<>();
public static void addActivity(Activity activity){
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishyAll(){
for(Activity activity:activities){ // 遍历
if(!activity.isFinishing()){
activity.finish();
}
}
activities.clear();
}
}
修改BaseActivity
public class BaseActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("BaseActivity", getClass().getSimpleName());
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
活动中添加鼠标监听
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("ThirdAcitivity", "Task id is "+getTaskId());
setContentView(R.layout.thrid_activity);
Button button3 = (Button) findViewById(R.id.button_3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ActivityCollector.finishyAll();
}
});
}
这是我学习Android的笔记,参考书<<第一行代码-第二版>>,感谢郭霖大神
如有不足之处,可以一起讨论
附上郭霖的blog http://blog.csdn.net/guolin_blog
网友评论