Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android - overridden volume button has affected back button?

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?

like image 948
jwbensley Avatar asked Mar 26 '11 23:03

jwbensley


2 Answers

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.

like image 59
AndyMac Avatar answered Sep 27 '22 18:09

AndyMac


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);
like image 36
Evan Avatar answered Sep 27 '22 18:09

Evan