-->

Android: Key Event from Android Box remote control

2019-06-19 17:40发布

问题:

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;
}