How to Manage Audio Focus in Android?
The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenly there is an incoming call then the audio file needs to be stopped and after the call is ended the Audio should continue playing from where it has stopped. In this article, it’s been discussed how to handle the Audio interruptions or how to implement the Audio Focus in Android. Have a look at the following image to get an idea of what things are going to be discussed. Note that we are going to implement this project using the Java language.
Steps to Implement the Audio Focus or handle Audio interruptions
Step 1: Create an empty activity project
- Create an empty activity Android Studio project. And select Java as a programming language.
- To know how to create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
- The main layout in this project includes only three buttons which are used to play, pause, and to stop the Audio file playing in the application.
- Invoke the following code to implement the UI.
Step 3: Working with the MainActivity.java file
- The main Callback needs to implemented when there is a change in the Audio focus. Meaning the system has transferred the audio focus to another service that is used by the app, in this case, the Phone application which takes the audio focus from the current application which is playing the audio.
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener -> This handles if there is change in the audio focus which the callback need to implemented according to the focus change from the audio manage.
- When the call gets hanged up the focus changes to the current application and MediaPlayer is resumed.
- The focus request result which is returned by the Android system is compared to the following constants.
- AUDIOFOCUS_GAIN: if the system grants the audio focus gain, then the playback can be continued after the temporary loss of the audio focus.
- AUDIOFOCUS_LOSS_TRANSIENT: if there is temporary loss of audio focus then the playback of the audio should be paused.
- AUDIOFOCUS_LOSS: if there is permanent loss of the audio then the mediaplayer should be released (completely stopped).
- To implement the Audio focus in the application same as discussed above invoke the following code in the MainActivity.java file. Comments are added for better understanding.
Note: When there is no requirement of audio focus, abandonAudioFocusRequest method needs to be called with the AudioManager instance and it requires the parameter AudioFocusRequest focusRequest which needs to be passed.