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
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);
}
}
-
6Sweet. You have to 'return true;' after doing your thing to suppress the phone's default volume behavior. Commented Mar 2, 2010 at 23:11
-
10Also 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
-
4Or you could override dispatchKeyEvent(KeyEvent event) method. Commented Oct 28, 2010 at 16:49
-
4The 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."– MarkCommented Oct 5, 2011 at 14:42
-
What is the difference between the onKeyDown() and onKeyUp() Methods ? Commented Sep 17, 2016 at 20:40
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);
}
}
-
3This is the correct answer. Using onKeyDown or onKeyUp still gives the default sound of changing the volume.– korbesCommented Aug 27, 2014 at 1:16