问题
I'm trying to override Back button to stop an audio player and close media player activity, but I noticed that volume buttons are not working anymore. I imagine there is a mistake in overriding code. PS. in my MediaController
I override hide()
method to always show controls.
mediaController = new MediaController(this)
{
@Override
public void hide() {
// TODO Auto-generated method stub
//do nothing
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
super.hide();
Activity a = (Activity)getContext();
a.finish();
}
return true;
}
};
回答1:
Your problem is in dispatchKeyEvent():
You are using return true
for all the HW Keys and this stops all keys from responding,
whereas you should be using
return super.dispatchKeyEvent(event);
For keys other than Back Key.
So your code should be something like this:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
finish();
return true;
}
**return super.dispatchKeyEvent(event);**
}
回答2:
You could overide onBackPressed() instead.
回答3:
You should use like this
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
finish();
return true;
}
return false;
}
Out the code from method or try :
@Override
public void onBackPressed() {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
finish();
}
or
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
回答4:
Did you tried this check it once it may solve your issue
@Override
public void onBackPressed() {
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}
finish();
}
来源:https://stackoverflow.com/questions/23338989/android-overriding-back-button-causes-volume-buttons-stop-working