Android: Key Event from Android Box remote controller

断了今生、忘了曾经 提交于 2019-12-10 14:00:03

问题


I was interested to know how can i catch key/button events from Android TV Box remote controller?

For example, i want a popup menu to show when i click the OK button from remote controller. And i want to catch the next/back key events from remote controller.

Should i use the Key Event class from Android, if yes how should i implement it?

I came across this function but i cannot really make sense of it.

 @Override 
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
        {
            //your Action code
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

Thanks in advance.


回答1:


You should catch key event on dispatchKeyEvent

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        Log.e(TAG, "Key down, code " + event.getKeyCode());

    } else if (event.getAction() == KeyEvent.ACTION_UP) {
        Log.e(TAG, "Key up, code " + event.getKeyCode());
    }

    return true;
}

Edit: First, you should know key map of your remote (it is not the same for all kind of Android TV box), the code above will help you know code of key that you press on the remote. For example, i got key code 3 when i press button BACK on remote. Then, i want when back key pressed, a Toast message will be show:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    // You should make a constant instead of hard code number 3.
    if (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode == 3) {
        Toast.makeText(this, "Hello, you just press BACK", Toast.LENG_LONG).show();

    } 
    return true;
}


来源:https://stackoverflow.com/questions/29251392/android-key-event-from-android-box-remote-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!