Android: How to stop the music service of my application if another application is playing music.?

1) In an Android project, I wrote a service that plays music in the background. The problem is that my application plays music in the background, and another application (music player) plays music, audio systems play at the same time. I want to stop playing music in my application if any other application plays music. How can I handle this?

+4
source share
3 answers

This concept is called audio focus in Android.

, - , , (, ..).

OnAudioFocusChangeListener.

, :

  • .
  • , .
  • , .
  • , (""), .

, Managing Audio Focus Android.

+7

.

OnAudioFocusChangeListener listener

AudioManager

private AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);

@ 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;
  }
}
+7
 private boolean reqAudioFocus() {
        boolean gotFocus = false;
        int audioFocus = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (audioFocus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            gotFocus = true;
        } else {
            gotFocus = false;
        }
        return gotFocus;
    }

, . , .

 if (reqAudioFocus()) {

            mPlayer.prepareAsync();
        }

, .

,

public void onAudioFocusChange(int focusChange) {

        if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            am.abandonAudioFocus(this);
            mPlayer.stop();


        }

    }

"am" - AudioManager.

AudioManager.OnAudioFocusChangeListener

0

Source: https://habr.com/ru/post/1548199/


All Articles