Android开发之点击两次Back键退出App

Back按键的方法是onKeyDown()方法,重写该方法就可以改变back按键的作用。

实现点击两次Back按键退出app,有两种方法:

方法1.

     private static boolean isAppExit=false;  //定义一个变量,标示是否退出
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
isAppExit = false;
}
};
     @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { //重写onKeyDown()方法
// TODO Auto-generated method stub
if (keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0) {
exit();
return true;
}
return super.onKeyDown(keyCode, event);
} private void exit() {
if (!isAppExit) {
isAppExit = true;
Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
Toast.LENGTH_SHORT).show();
// 利用handler延迟发送更改状态信息
mHandler.sendEmptyMessageDelayed(0, 2000);
} else {
this.finish();
}
}

方法2.

     private long clickTime = 0; //记录第一次点击的时间
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return true;
}
return super.onKeyDown(keyCode, event);
} private void exit() {
if ((System.currentTimeMillis() - clickTime) > 2000) {
Toast.makeText(getApplicationContext(), "再按一次后退键退出程序",
Toast.LENGTH_SHORT).show();
clickTime = System.currentTimeMillis();
} else {
Log.e(TAG, "exit application");
this.finish();
}
}
上一篇:上传自己的Python代码到PyPI


下一篇:Nginx访问限速配置方法详解