http://blog.csdn.net/look85/article/details/23740761
dispatchKeyEvent和onKeyDown关系:
当键盘按下时
首先触发dispatchKeyEvent
然后触发onUserInteraction
再次onKeyDown
如果按下紧接着松开,则是俩步
紧跟着触发dispatchKeyEvent
然后触发onUserInteraction
再次onKeyUp
1)当我们重写了onKeyDown方法后,如果return false,则会继续调用系统的onKeyDown方法。
如果只想让程序调用自己写的onKeyDown,则需要return true。
利用该特性可以拦截耳机耳机按键,防止启动音乐。
下面转载一下拦截屏幕按键的方法:
ComponentonKeyDown监控 1、拦截/屏蔽返回键、菜单键实现代码
2、拦截/屏蔽系统Home键
1 2 3 4 |
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } |
为什么必须重写onAttachedToWindow(),看看下面的代码就知道了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
/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; } } } } |
onKeyDownonKeyDown方法比较好。