1//set the listener (this should be global)
2AudioManager.OnAudioFocusChangeListener audioListener = new AudioManager.OnAudioFocusChangeListener() {
3 @Override
4 public void onAudioFocusChange(int i) {
5 //code to hundle diffrent kind of focus states.
6 }
7};
8
9
10
11//set the request
12audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
13audioManager.requestAudioFocus(audioListener , AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
14
15if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
16 // You now have the audio focus and may play sound.
17}else if (focusChange == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
18 // Handle the failure.
19}
20
21