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.?
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;
}
}
This concept is called audio focus in Android.
In broad terms, it means that only one app can have audio focus at one point in time, and that you should relinquish if it asked to (for example if a phone call arrives, or another app wants to play music, &c).
To do this, you need to register an OnAudioFocusChangeListener
.
Basically, you must:
Please check the Managing Audio Focus article in the Android documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With