Reputation: 12327
I have code that allows a user to issue an audible alert on their device. In Android 2.3 and below, I am able to issue the alert even if the sound is turned all the way down by programatically increasing the volume via AudioManager.setStreamVolume
. However now in Android 3.x and up when I attempt to do this the native volume adjustment widget appears on the screen for a moment but the current volume still stays at zero. The code is below:
int currentVolume = audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioMgr.setStreamMute(AudioManager.STREAM_MUSIC, false);
// If the current volume is not set to the maximum level
if (currentVolume < maxVolume) {
// Set the current volume to the maximum level
audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.ADJUST_RAISE);
}
My question is...what has changed in Honeycomb that makes this no longer work? I set a breakpoint after setStreamVolume
and ran getStreamVolume
by hand. It was still set to zero. Thoughts?
Upvotes: 2
Views: 801
Reputation: 281
With ICS (Android 4.0.3) the problem remains but there is a working solution as well. Try using this code:
// The commented code below works with 2.3, but not with 4.0 (ICS)
//audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, lvl, 0);
// Use this instead
while(audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC) > lvl) {
audioMgr.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
}
while(audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC) < lvl) {
audioMgr.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
}
Upvotes: 3
Reputation: 12327
So it seems that setStreamVolume
is ignored, but adjustStreamVolume
is not. I still have to do more testing on non-Honeycomb devices but thus far this code appears to work:
while(audioMgr.getStreamVolume(AudioManager.STREAM_MUSIC) < maxVolume) {
audioMgr.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
}
Upvotes: 0