【Android开发中拦截或屏蔽返回键】在Android开发中我们常常会遇到需要拦截或屏蔽返回键的 需求,对拦截后的返回键进行特殊操作
这里写代码片public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((System.currentTimeMillis() - mExitTime) > 2000) {// System.currentTimeMillis()无论何时调用,肯定大于2000
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
mExitTime = System.currentTimeMillis();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MENU) {
System.out.println("您按了菜单键");
CreatAlertDialog("您按了菜单键");
Toast.makeText(this, "您按了菜单键", Toast.LENGTH_SHORT).show();
return true;
} else if (keyCode == KeyEvent.KEYCODE_HOME) {
// 由于Home键为系统键,此处不能捕获,需要重写onAttachedToWindow()
System.out.println("您按了HOME键");
CreatAlertDialog("您按了HOME键");
Toast.makeText(this, "您按了HOME键", Toast.LENGTH_SHORT).show();
return true;
}
return super.onKeyDown(keyCode, event);
}private void CreatAlertDialog(String str){
new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
.setMessage(str)
.show();
}
返回true时则禁掉返回键;
2, dialog对话框拦截返回键
Dialog dialog = new Dialog(this, R.style.loginDialogTheme);
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){//监听返回键
System.exit(0);
}
return false;
//返回键可用,点击返回键退出应用
}
});
3,frgment 消耗返回事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {if (mHomeTabIndexEnum != null) {
// 将返回键分给fragment处理
Fragment currentFragment = mFragmentManager
.findFragmentByTag(mHomeTabIndexEnum.toString());
if (mHomeTabIndexEnum == HomeTabIndexEnum.TAB_HOME_LIVE_CHINA) {
LiveChinaFragment liveChinaFragment = (LiveChinaFragment) currentFragment;
// 消费了返回事件
boolean onkeyDownBack = liveChinaFragment.onkeyDownBack();
if (onkeyDownBack) {
return true;
}
} else if (mHomeTabIndexEnum == HomeTabIndexEnum.TAB_HOME_PANDA_LIVE) {
LovePandaFragment lovePandaFragment = (LovePandaFragment) currentFragment;
// 消费了返回事件
boolean onkeyDownBack = lovePandaFragment.onkeyDownBack();
if (onkeyDownBack) {
return true;
}
}
}
long now = new Date().getTime();
if (now - mLastBackTime < 2000) {// getSharedPreferences("config",
// MODE_PRIVATE).edit().clear().commit;
return super.onKeyDown(keyCode, event);
} else {
mLastBackTime = now;
Toast.makeText(MainActivity.this, "连续点击两次退出应用!!!",
Toast.LENGTH_SHORT).show();
}
return true;
}
return super.onKeyDown(keyCode, event);
}