0

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.

Jeromy Irvine
  • 11,614
  • 3
  • 39
  • 52
Sandeep
  • 2,573
  • 3
  • 21
  • 28

2 Answers2

0

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

Community
  • 1
  • 1
Ahmad
  • 437
  • 5
  • 20
  • hey , buddy Ahmad .the question is that, i am asking how to detect Menu + Back or any other Key combination which is being pressed simultaneously..**Note** i am talking about key combination , not detection of single key .. – Sandeep Dec 29 '12 at 06:34
  • I thinks you can do it by overriding onKeyDown event and in it you should use thread to get another key to compare. With this solution at first you get first key and run thread to get second key, if they are the same key as you want then you can call your method. – Ahmad Dec 29 '12 at 06:51
0

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.

Sathirar
  • 331
  • 4
  • 17