I have a player app with a seekbar for volume control inside. I use this code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
int index = volumeSeekbar.getProgress();
volumeSeekbar.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
int index = volumeSeekbar.getProgress();
volumeSeekbar.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
The code works well. Now when I press hardware volume control down/up button my seekbar moves. But now I have an issue with the volume dialog in Android. When i press the hardware button it doesn’t show anymore. I mean the dialog in the picture:

What can I do to fix it and show the volume dialog as usual?
Edit:
Here is my code for using AudioManager:
private void initControls() {
try {
volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar arg0) {}
@Override
public void onStartTrackingTouch(SeekBar arg0) {}
@Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
}
});
}
...
}
The dialog is not shown because you are consuming the key event in the
onKeyDown()function. Therefore the event is not propagated further and the volume dialog is not shown.There is a simple solution for this. In the documentation for the
onKeyDown()function it says that you have to returnfalseto prevent the event from being consumed. Now the dialog will show again.Nevertheless, I don’t think you are using the right approach to receive the information about volume. When the volume dialog shows up, the user can drag the seekbar in it and change the volume, such change is not reflected in calls to
onKeyDown()function. You could utilizeAudioManagerand itsgetStreamVolume()function: