Android系统onKeyDown监控/拦截/监听/屏蔽返回键、菜单键和Home键

protected void dialog() {
AlertDialog.Builder builder = new Builder(TestActivity.this);
builder.setMessage("确定要退出吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
TestActivity.this.finish();
}
});
builder.setNegativeButton("取消",
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键
dialog();
return false;
} else if(keyCode == KeyEvent.KEYCODE_MENU) {
// rl.setVisibility(View.VISIBLE);
Toast.makeText(TestActivity.this, "Menu", Toast.LENGTH_SHORT).show();
return false;
} else if(keyCode == KeyEvent.KEYCODE_HOME) {
//由于Home键为系统键,此处不能捕获,需要重写onAttachedToWindow()
Toast.makeText(TestActivity.this, "Home", Toast.LENGTH_SHORT).show();
return false;
}
return super.onKeyDown(keyCode, event);
}
// 拦截/屏蔽系统Home键
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}

posted @ 2013-01-08 16:44  与时俱进  阅读(44604)  评论(1编辑  收藏  举报
友情链接:同里老宅院民居客栈