Android监听返回键需重写onKeyDown()方法
Home键keyCode==KeyEvent.KEYCODE_HOME
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
- //++自定义点击事件
- return true;//不执行父类的点击事件
- }
- return super.onKeyDown(keyCode, event);//继续执行父类的其他点击事件
- }
实例:再按一次返回键退出应用
- private long exitTime = 0;
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
- if((System.currentTimeMillis()-exitTime) > 2000){
- Toast.makeText(getApplicationContext(), "再按一次退出应用", Toast.LENGTH_SHORT).show();
- exitTime = System.currentTimeMillis();
- } else {
- finish();
- System.exit(0);
- }
- return true;
- }
- return super.onKeyDown(keyCode, event);
- }