• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Android:How to run code depending on simultaneous hard key press?

angelasim

Lurker
I am trying to implement a functionality when i press the VOLUME DOWN and POWER BUTTON simultaneously; i must be able to run a method code inside my Activity.

public boolean onKeyUp(int keyCode, KeyEvent event)
{
}
From my initial search; it seems that only one such key press event is acknowledged at a time in Android usng the onKeyUp method. Is it true?

In my Android phone, on simultaneously pressing POWER BUTTON as well as MENU BUTTON i am able to capture a screen shot.

Does this feature not acknowledge simultaneous key presses?
 
I have no idea if this might work - but how about you set a timer when either the volume down or power button is pressed - assume you wait 300 milliseconds. If the other button is pressed within that period you pass that as a simultaneous key press. I think the risk is pretty low that the user presses both buttons at the exact same millisecond.
 
Have two boolean flags, one for each button.
For each button, have key up and key down events, the key up making the relevant flag false and true when down.
A simple check of seeing whether both flags are true will allow you do what you wanted to happen.
For example:

Boolean powerFlag=false, volFlag=false;

public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_POWER) { powerFlag= false;
return true
} if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { volFlag= false;
return true
} return super.onKeyUp(keyCode, event); }
public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { volFlag=true; if (powerFlag) { //Do whatever }
return true; } if (keyCode == KeyEvent.KEYCODE_POWER) { powerFlag=true; if (volFlag) { //Do whatever }
return true; } return super.onKeyDown(keyCode, event); }

Something like this will probably work (I used something similar in my Shooting Watch app).

Thanks.
 
Back
Top Bottom