28

I'd like to use the volume buttons for something else in my Android application. The Dolphin browser does this I am told. Anyone know how?

2 Answers 2

38

I imagine it looks something like this:

public boolean onKeyDown(int keyCode, KeyEvent event) 
{ 
   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 
       // Do your thing 
       return true;
   } else {
       return super.onKeyDown(keyCode, event); 
   }
}
5
  • 6
    Sweet. You have to 'return true;' after doing your thing to suppress the phone's default volume behavior. Commented Mar 2, 2010 at 23:11
  • 10
    Also to completely suppress the default behavior you should also catch the events and return true in an onKeyUp() override. Commented Mar 3, 2010 at 11:08
  • 4
    Or you could override dispatchKeyEvent(KeyEvent event) method. Commented Oct 28, 2010 at 16:49
  • 4
    The dispatchKeyEvent(KeyEvent event) method is the better choice. If I use onKeyDown(...) it still gets through to the AudioManager and I get the following debug Message even though I am returning true: "AudioHardwareQSD(3394): AudioHardware pcm playback is going to standby."
    – Mark
    Commented Oct 5, 2011 at 14:42
  • What is the difference between the onKeyDown() and onKeyUp() Methods ?
    – Ajay Sivan
    Commented Sep 17, 2016 at 20:40
37

in your activity,

 @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            return true;
        default:
            return super.dispatchKeyEvent(event);
        }
    }
1
  • 3
    This is the correct answer. Using onKeyDown or onKeyUp still gives the default sound of changing the volume.
    – korbes
    Commented Aug 27, 2014 at 1:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.