1.新建一个ActivityCollector类用于存放并操作Acitivity实例。
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) { activity.finish(); } } // 获取当前开启的activity数量 public static int getListSize() { return activities.size(); } }
2.在每个Activity中添加代码:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_one); ActivityCollector.addActivity(this); }
protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); }
3.在想要双击back键退出应用的Activity中添加代码:
private long exitTime = 0; @Override public void onBackPressed() { // super.onBackPressed(); if ((System.currentTimeMillis() - exitTime) > 2000) { Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { if (ActivityCollector.getListSize() > 0) { ActivityCollector.finishAll(); } System.exit(0); } }