主要还是说返回键把,home键如果处理比较流氓,而且Android也不想我们去处理。
第一种(如果手机也有其他的各种物理键都可以在这个方法里面处理):
1 @Override 2 public boolean onKeyDown(int keyCode, KeyEvent event) { 3 if (keyCode==KeyEvent.KEYCODE_BACK){ 4 backToRoarMain(); 5 return false; 6 } 7 8 return super.onKeyDown(keyCode, event); 9 }
第二种:只适合返回键:
@Override public void onBackPressed() { super.onBackPressed(); }
都是可以的。
home键需要处理的也比较少。
第一,我们也是在onKeyDown里面先拦截:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_MENU) { //监控/拦截菜单键 } else if(keyCode == KeyEvent.KEYCODE_HOME) { //由于Home键为系统键,此处不能捕获,需要重写onAttachedToWindow() } return super.onKeyDown(keyCode, event); }
接下来重写onAttachedToWindow()
public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }
欧了。
然后为什么要重写,不重写会怎么样?
看下面:
/frameworks/policies/base/phone/com/android/internal/policy/impl/PhoneWindowManager.java 1000行附近 if (code == KeyEvent.KEYCODE_HOME) { // If a system window has focus, then it doesn't make sense // right now to interact with applications. WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null; if (attrs != null) { final int type = attrs.type; if (type == WindowManager.LayoutParams.TYPE_KEYGUARD || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) { // the "app" is keyguard, so give it the key return false; } final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length; for (int i=0; i<typeCount; i++) { if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) { // don't do anything, but also don't pass it to the app return true; } } } }
其实我们重写View的onKeyDown也是可以的,前提是有焦点,所以保险还是直接重写activity的吧。