Android : How to stop music service of my app, if another app plays music.?
android, audio, service
Solution
This is how I solved the issue.
Implement `OnAudioFocusChangeListener listener`
Initialise `AudioManager` like
private AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Request Audio focus
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
@Overide the following method of `OnAudioFocusChangeListener`
public void onAudioFocusChange(int focusChange)
{
switch (focusChange)
{
case AudioManager.AUDIOFOCUS_GAIN:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
resumePlayer(); // Resume your media player here
break;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
pausePlayer();// Pause your media player here
break;
}
}
Problem
1) In an android project, I have written a service that plays music at the background. The problem is when my application is playing music at the background and another application(music player) plays music, both the audios play simultaneously. I want to stop playing the music in my application, if any other app plays the music. How do I deal with this.?