I am developing a Song Player App using ExoPlayer. The problem I am currently having is that, on Android 7.x devices, the user is being able to listen to two players at the same time. It seems to be a thing of the new Android versions.
I would like to know if is it possible to avoid this behavior, making the user unable to listen to two players while listening to a media on my app.
You probably need to manage Audio focus in your application. You can have a look here : https://developer.android.com/guide/topics/media-apps/audio-focus.html
To avoid every music app playing at the same time, Android introduces the idea of audio focus. Only one app can hold audio focus at a time.
When your app needs to output audio, it should request audio focus.
AudioManager mAudioManager_ = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener_ = new AudioManager.OnAudioFocusChangeListener()
{ @Override
public void onAudioFocusChange (int focusChange)
{ switch (focusChange)
{ case AudioManager.AUDIOFOCUS_GAIN:
Log.e("DEBUG", "##### AUDIOFOCUS_GAIN");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.e("DEBUG", "##### AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.e("DEBUG", "##### AUDIOFOCUS_LOSS");
break;
}
}
};
if (mAudioManager_.requestAudioFocus(mOnAudioFocusChangeListener_, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
{ // start play
// ...
mAudioManager_.abandonAudioFocus(mOnAudioFocusChangeListener_);
}