Example usage for android.media AudioManager requestAudioFocus

List of usage examples for android.media AudioManager requestAudioFocus

Introduction

In this page you can find the example usage for android.media AudioManager requestAudioFocus.

Prototype

public int requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint) 

Source Link

Document

Request audio focus.

Usage

From source file:com.fastbootmobile.encore.service.PlaybackService.java

/**
 * Request the audio focus and registers the remote media controller
 *///from www  . j  a v a 2 s  .co  m
private synchronized void requestAudioFocus() {
    if (!mHasAudioFocus) {
        final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        // Request audio focus for music playback
        int result = am.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            am.registerMediaButtonEventReceiver(RemoteControlReceiver.getComponentName(this));

            // Notify the remote metadata that we're getting active
            mRemoteMetadata.setActive(true);

            // Register AUDIO_BECOMING_NOISY to stop playback when earbuds are pulled
            registerReceiver(mAudioNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

            // Add a WakeLock to avoid CPU going to sleep while music is playing
            mWakeLock.acquire();

            mHasAudioFocus = true;
        } else {
            Log.e(TAG, "Audio focus request denied: " + result);
        }
    }
}

From source file:dk.nota.lyt.libvlc.PlaybackService.java

private void changeAudioFocus(boolean acquire) {
    final AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (am == null)
        return;//from   w w w.  jav  a2  s  . c  o  m

    if (acquire) {
        if (!mHasAudioFocus) {
            final int result = am.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN);
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                am.setParameters("bgm_state=true");
                mHasAudioFocus = true;
            }
        }
    } else {
        if (mHasAudioFocus) {
            final int result = am.abandonAudioFocus(mAudioFocusListener);
            am.setParameters("bgm_state=false");
            mHasAudioFocus = false;
        }
    }
}