Stop MediaPlayer when an other app play music

You should use AudioManager service to receive notification whether you receive/lost audio focus (Managing audio focus). I’ve done similar thing in a project where when my app starts playing, Google Play pause and vice versa. Use the following code where you are controlling your media playback like (activity or service)-

// Add this code in a method

AudioManager am = null;

// Request focus for music stream and pass AudioManager.OnAudioFocusChangeListener
// implementation reference
int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, 
                AudioManager.AUDIOFOCUS_GAIN);

if(result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{
    // Play
}

// Implements AudioManager.OnAudioFocusChangeListener

@Override
public void onAudioFocusChange(int focusChange) 
{
    if(focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
    {
        // Pause
    }
    else if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
    {
        // Resume
    }
    else if(focusChange == AudioManager.AUDIOFOCUS_LOSS)
    {
        // Stop or pause depending on your need
    }
}

Leave a Comment