再按一次返回键退出最终完整方案:
boolean isExit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyApplication.getInstance().addActivity(this);
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 再按一次退出 exit(); return false; } else { return super.onKeyDown(keyCode, event); } } private void exit() { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); mHandler.sendEmptyMessageDelayed(0, 2000); } else { MyApplication.getInstance().exit(); } } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); isExit = false; } };
完整退出:
之前的退出方案,经常会退出不完全。
Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); System.exit(0);
替代方案:
一种比较流行的Android经典完美退出方法,使用单例模式创建一个Activity管理对象,该对象中有一个Activity容器(具体实现自己处理,使用LinkedList等)专门负责存储新开启的每一个Activity,并且容易理解、易于操作,非常不错!
MyApplication类(储存每一个Activity,并实现关闭所有Activity的操作)
public class MyApplication extends Application { private List<Activity> activityList = new LinkedList<Activity>(); private static MyApplication instance; private MyApplication() { } //单例模式中获取唯一的MyApplication实例 public static MyApplication getInstance() { if(null == instance) { instance = new MyApplication(); } return instance; } //添加Activity到容器中 public void addActivity(Activity activity) { activityList.add(activity); } //遍历所有Activity并finish public void exit() { for(Activity activity:activityList) { activity.finish(); } System.exit(0); } }
在每一个Activity中的onCreate方法里添加该Activity到MyApplication对象实例容器中 MyApplication.getInstance().addActivity(this); 在需要结束所有Activity的时候调用exit方法 MyApplication.getInstance().exit();