Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : How to stop music service of my app, if another app plays music.? [closed]

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.?

like image 249
Umesh Isran Avatar asked Dec 09 '22 07:12

Umesh Isran


2 Answers

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;
  }
}
like image 141
Umesh Isran Avatar answered Dec 11 '22 11:12

Umesh Isran


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:

  • Request audio focus before starting playback.
  • Only start playback if you effectively obtain it.
  • Abandon focus when you stop playback.
  • Handle audio focus loss, either by lowering volume temporarily ("ducking") or stopping playback altogether.

Please check the Managing Audio Focus article in the Android documentation.

like image 25
matiash Avatar answered Dec 11 '22 11:12

matiash