首页 > 代码库 > android按键复用

android按键复用

  最近做android电视系统定制,上面安排我做一个按键板按键复用的功能:当电视的OSD菜单显示出来时按键板上的 ch+/ch- 复用为方向键上/下,vol+/vol- 复用为方向键 右/左。  OSD 菜单是使用一个Fragment实现,所以选择在 OSD 菜单显示(onResume)触发按键复用功能,在 OSD 菜单消失(onStop)时取消按键复用功能。实现的思路是合理的了,我们知道应用程序处理按键事件 KeyEvnet 通常是通过事件的keyCode值决定程序要做什么事,所以只需在处理按键函数 onKey,onKeyUp,onKeyDown 等处理按键事件前修改事件的keyCode值就可以实现按键的复用了,具体到这里就是把 KEYCODE_CHANNEL_UP/KEYCODE_CHANNEL_DOWN 改为 KEYCODE_DPAD_UP/KEYCODE_DPAD_DOWN 同样的把 KEYCODE_VOLUME_UP/KEYCODE_VOLUME_DOWN 改为 KEYCODE_DPAD_RIGHT/KEYCODE_DPAD_LEFT。 要在上面提到的函数前修改键值就需要用到 dispatchKeyEvent(KeyEvent event) 了,官方对该方法的解释是在按键事件被分发到窗口前将其拦截。好了闲话少说代码如下:  

 1 public boolean dispatchKeyEvent(KeyEvent event) { 2         long downTime= event.getDownTime(); 3         long eventTime = event.getEventTime(); 4         int  action = event.getAction(); 5         int  code = event.getKeyCode(); 6         int repeat = event.getRepeatCount(); 7         int metaState = event.getMetaState(); 8         switch (code) { 9         case KeyEvent.KEYCODE_CHANNEL_UP:10                 event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_UP, repeat, metaState);11             break;12         case KeyEvent.KEYCODE_CHANNEL_DOWN:13             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_DOWN, repeat, metaState);14             break;15         case KeyEvent.KEYCODE_VOLUME_UP:16             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_RIGHT, repeat, metaState);17             break;18         case KeyEvent.KEYCODE_VOLUME_DOWN:19             event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_DPAD_LEFT, repeat, metaState);20             break;21         }22 23         return super.dispatchKeyEvent(event);24     }

 

 

android按键复用