Using the code below I have stopped the use of the volume buttons unless I am streaming audio (otherwise it annoyingly changes the ringer volume), but the 'Back' button isn't working.
Pressing 'back' should got to my phones desktop (or exit my app, like you would expect), but it isn't doing anything. If I open the menu, 'Back' will close the menu as it should, but I can't leave the app.
I have copied the code onto other activities within my app, if I open another activity within my app, because the 'Back' button isn't working, I can't go back to the main screen :)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Suppress the use of the volume keys unless we are currently listening to the stream
if(keyCode==KeyEvent.KEYCODE_VOLUME_UP) {
if(StreamService.INT_PLAY_STATE==0){
return true;
}else{
return false;
}
}
if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN) {
if(StreamService.INT_PLAY_STATE==0){
return true;
}else{
return false;
}
}
return false;
Why is this happening?
Haven't tested, but I think you need to include an else where you call super.onKeyDown, ie:
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
code
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
more code
} else {
super.onKeyDown(keyCode, event);
}
Otherwise, you're capturing all keycodes and returning false after checking the volume codes.
A simpler and more robust way to have the volume keys always control the Media volume is to insert this line into your Activity's onCreate()
:
setVolumeControlStream(AudioManager.STREAM_MUSIC);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With