Reputation: 3275
I'm trying to play a radio stream with media type STREAM_ALARM and change its volume using the hardware buttons.
It needs to be STREAM_ALARM because it actually is an alarm: it should play through speakers even when headphones are plugged in and/or phone is set to silent.
I'm looking for an implementation that always works, whatever activity the user is in (so it should also work in, for example, the homescreen). I know I can override onKeyUp/Down but that only works in my activity)
Here's what I do now (simplified code)
audioMgr.requestAudioFocus(
afChangeListener,
AudioManager.STREAM_ALARM,
AudioManager.AUDIOFOCUS_GAIN
);
if (mp!=null) { mp.release(); mp = null;}
mp = new MediaPlayer();
mp.setDataSource(streamUrl);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setOnPreparedListener(onPreparedListener);
mp.prepareAsync();
And then when onPreparedListener fires:
mp.start();
But when then I press the volume buttons on my phone it changes the media volume instead of the alarm (tested with Android 4.4 and 5.0)
Android documentation says the following:
"By default, pressing the volume controls modify the volume of the active audio stream."
Source: http://developer.android.com/training/managing-audio/volume-playback.html#HardwareVolumeKeys
So I guess the question is: how do I (correctly) set the STREAM_ALARM as the active audio stream?
Or am I doing something wrong?
Thanks in advance!
UPDATE: I've reported this as a bug on the AOSP Bug Tracker and it got accepted.. so I guess this actually should work as I described above but it doesn't :S
Link: https://code.google.com/p/android/issues/detail?id=183843
Upvotes: 3
Views: 752
Reputation: 3275
To answer my own question: it turns out that Google thinks it makes total sense that the hardware volume buttons always control "what you hear" except when it is an alarm. THEN you have to go into the app and use the volume buttons:
Volume keys never control alarm stream volume by default. They do in clock app or when the alarm volume slider is active in the volume panel.
An application must call Activity.setVolumeControlStream() with ALARM stream to have the volume keys control the ALARM stream volume
Status: WorkingAsIntended
https://code.google.com/p/android/issues/detail?id=183843
So I'm not doing anything wrong, it's by design that Android is behaving inconsistent when it comes to controlling sound with volume buttons. By. Design. :(
Upvotes: 1
Reputation: 707
If the user is in your Activity and using the hardware keys add:
setVolumeControlStream(AudioManager.STREAM_ALARM);
and the alarm stream will be controlled.
Upvotes: 0
Reputation: 93614
Override the activity's onKeyDown(). Look for the volume buttons being pressed. When it happens, set a new volume via setStreamVolume.
Upvotes: 0