Android两次后退键退出
转载请注明出处:http://blog.csdn.net/javacattle/article/details/41964045
仅仅要在 *.Java 文件里加入就可以
private int back = 0; //===============back两次退出===================== @Override public boolean onCreateOptionsMenu(Menu menu) {//必要的改变 menu.add(0, 2, 2, "退出"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 2: Myback(); break; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) {//两次back退出 if (keyCode == KeyEvent.KEYCODE_BACK) { back++; switch (back) { case 1: Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show(); break; case 2: back = 0;// 初始化back值 Myback(); break; } return true;// 设置成false让back失效 ,true表示 不失效 } else { return super.onKeyDown(keyCode, event); } } public void Myback() { // 关闭程序 MainActivity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程 }
private int tDifference = 2000;//等待的时间 private boolean isExit = false; //状态 private Timer mTicker = null;//定义Timer时间器 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {// 两次back退出 if (keyCode == KeyEvent.KEYCODE_BACK) { Myback(); return true; } else { return super.onKeyDown(keyCode, event); } } public void Myback() { // 关闭程序 if(isExit){ MainActivity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid());// 关闭进程 }else{ Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show(); isExit = !isExit; if(null == mTicker){ mTicker = new Timer(); } mTicker.schedule(new TimerTask() { @Override public void run() {//改变标识 isExit = false; } },tDifference ); } }
PS:android上本人菜鸟一枚,不喜勿喷