This post explains how to stop other application that plays music in background (Media player, Spotify, Deezer,…) and play audio from your app. Also, the second part explains how, when your audio stop playing, to release audio focus from your app and the audio apps in background to continue from where they stopped.
Get Audio Focus:
Get AudioManager System Service for providing access to volume and ringer mode control. Send a request to obtain the audio focus from the OS and to pause all background music.
Release Audio focus and continue background audio apps:
Stopping or pausing audio from app and releasing focus for other apps to play audio. It is abandoning audio focus listener (it is abandoning/setting to null)
The example implementation, have included API 26 and above support. API below 26 requestAudioFocus() is deprecated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public class AudioFocusManager { Context context; private AudioFocusRequest audioFocusRequest; public AudioFocusManager(Context context) { this.context = context; } public void requestAudioFocus() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT) .build(); getAudioManager().requestAudioFocus(audioFocusRequest); } else { getAudioManager().requestAudioFocus(null , AudioManager.STREAM_MUSIC , AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); } } public void releaseAudioFocus() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (audioFocusRequest != null) { getAudioManager().abandonAudioFocusRequest(audioFocusRequest); audioFocusRequest = null; } } else { getAudioManager().abandonAudioFocus(null); } } private AudioManager getAudioManager() { return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)); } } |