实现点击两次返回键退出
//第一步,定义一个变量,用于标识是否退出
boolean isExit;
//第二步,重写Activity中onKeyDown方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exit();
return false;
} else {
return super.onKeyDown(keyCode, event);
}
}
//第三步,写一个退出方法
public void exit(){
if (!isExit) {
isExit = true;
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
mHandler.sendEmptyMessageDelayed(0, 2000);
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
System.exit(0);
}
}
//第四步,根据exit()方法中的的消息,写一个Handler
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
isExit = false;
}
};