I am implementing a music player as a service, and would like to lower the volume of the music when a notification arrives to the phone.
This is what I do:
AudioManager audioManager = (AudioManager)getApplicationContext(). getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
and my listener is:
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
if (!mediaPlayer.isPlaying()){
mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
}
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.2f, 0.2f);
break;
default:break;
}
}
};
When a call comes in, it works perfectly. When I receive a sms, gmail, whatsapp, etc... notification, the listener does not capture the event.
I also tried with:
AudioManager audioManager = (AudioManager)getApplicationContext(). getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK);
like explains here: Managin Audio Focus
but the listener is not listening the notification imput anyway.
And I also tried implementing AudioManager.OnAudioFocusChangeListener in the Service but occurs the same, calls well handled, notifications not.
I have added this on manifest....
uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS
What can I do? Why notification doesn't change the AudioFocus ??