Android: a key event on the Android Box remote control

I was curious to know how I can catch key / button events from the Android TV Box remote control?

For example, I want a popup menu to appear when I press the OK button from the remote control. And I want to catch the next / previous key events from the remote control.

Should I use the key event class on Android, if so, how do I implement it?

I came across this function, but I can't figure it out.

 @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.

+4
source share
1 answer

You must catch the 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;
}

: -, ( Android TV), , . , key code 3, BACK . , , Toast:

@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;
}
+1

All Articles