How can I detect which key combination is being pressed?
For example I want to recognize Back and Menu button being pressed simultaneously or any key combination.
I would like to open my application on the basis on which key is being pressed.
How can I detect which key combination is being pressed?
For example I want to recognize Back and Menu button being pressed simultaneously or any key combination.
I would like to open my application on the basis on which key is being pressed.
I did a simple research and found this solution and it may work. You can detect Menu key pressed by the following code.
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getAction() == KeyEvent.ACTION_DOWN) {
//Start a new thread here and run a while loop for listening to "back pressed" and trigger the event you want if the back button is pressed
} else {
//stop the started thread above
return false;
}
}
Hope this might help you. Thnks.
As Daniel Lew said (Prompt user to save changes when Back button is pressed):
You're not quite on the right track; what you should be doing is overriding onKeyDown() and listening for the back key, then overriding the default behavior:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}
return super.onKeyDown(keyCode, event);
}
If you're only supporting Android 2.0 and higher, they've added an onBackPressed() you can use instead:
@Override
public void onBackPressed() {
// do something on back.
return;
}
This answer is essentially ripped from this blog post: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html