Requesting Audio Focus

suggest change

requestAudioFocus is given audioListener, which this snippet never declares. The changedListener created afterward is not passed to that call. AUDIOFOCUS_REQUEST_FAILED is a return value of requestAudioFocus, not a focus change delivered to onAudioFocusChange.

audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

audioManager.requestAudioFocus(audioListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

changedListener = new AudioManager.OnAudioFocusChangeListener() {
    @Override
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // You now have the audio focus and may play sound.
        }
        else if (focusChange == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
            // Handle the failure.
        }
    }
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents