软硬件环境

  • OTT Box 5.1.1
  • Android studio 3.0.1

前言

在做Android TV时经常会碰到遥控器的使用,同一款盒子会同时匹配多款遥控器,而对应遥控器的按键一般是不一样的,有的按键多,有的按键少,如果不巧用的是按键少的遥控器,那键值复用就不可避免了。本文就来实现通过复用左右键来实现音量加减的功能。

实现

通过在dispatchKeyEvent方法中拦截键值,进行重新装配KeyEvent对象,达到键值复用的目的。

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int keyCode = event.getKeyCode();
    int action = event.getAction();
    long downTime = event.getDownTime();
    long eventTime = event.getEventTime();
    int repeat = event.getRepeatCount();
    int metaState = event.getMetaState();

    switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_VOLUME_UP, repeat, metaState);
            break;

        case KeyEvent.KEYCODE_DPAD_LEFT:
            event = new KeyEvent(downTime, eventTime, action, KeyEvent.KEYCODE_VOLUME_DOWN, repeat, metaState);
            break;
    }

    return super.dispatchKeyEvent(event);
}

Comments

comments powered by Disqus