Reputation: 119
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.
Upvotes: 8
Views: 16442
Reputation: 1
Minor correction on Tien's answer. event.getKeyCode missing () and Toast.LENG_LONG missing TH. Corrected code below:
@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.LENGTH_LONG).show();
}
return true;
}
Upvotes: 0
Reputation: 2215
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;
}
Upvotes: 4