27

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

37

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. 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. Mar 3, 2010 at 11:08
  • 4
    Or you could override dispatchKeyEvent(KeyEvent event) method. 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
    Oct 5, 2011 at 14:42
  • What is the difference between the onKeyDown() and onKeyUp() Methods ?
    – Ajay Sivan
    Sep 17, 2016 at 20:40
36

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
    Aug 27, 2014 at 1:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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