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?
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);
Dude, just change the audio context on that activity to media volume:
http://developer.android.com/reference/android/media/AudioManager.html
EDIT:
private AudioManager audio;
Inside onCreate:
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Override onKeyDown:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return false;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//your code
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
//your code
return true;
} else {
super.onKeyDown(keyCode, event);
}
return true;
}
精彩评论