Android中某个类继承Activity的子类TabActivity时,重载Activity中的public boolean onKeyDown(int keyCode, KeyEvent event)方法时,点击按键时并得不到响应,解决的方法是:
public boolean dispatchKeyEvent(KeyEvent event) { if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){ if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { exit(); } return true; } return super.dispatchKeyEvent(event); }
退出应用程序:
public void exit() { new AlertDialog.Builder(this) .setTitle("退出") .setMessage("确定退出吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(startMain); System.exit(0); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }).show(); }
Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办?
1、加权限禁止Home键
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
2、
@Override public void onAttachedToWindow() { // TODO Auto-generated method stub if (true) { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); } super.onAttachedToWindow(); }
3、
public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_HOME && event.getRepeatCount()==0){ return false; }else{ return super.onKeyDown(keyCode, event); }
}
当一个人找不到出路的时候,最好的办法就是将当前能做好的事情做到极致,做到无人能及。