Example usage for android.media AudioManager AUDIOFOCUS_GAIN

List of usage examples for android.media AudioManager AUDIOFOCUS_GAIN

Introduction

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

Prototype

int AUDIOFOCUS_GAIN

To view the source code for android.media AudioManager AUDIOFOCUS_GAIN.

Click Source Link

Document

Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.

Usage

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

@Override
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
        mAudioFocused = false;/*from  ww w  .j av  a 2  s  .  com*/
        if (LOCAL_LOGD)
            log("AUDIOFOCUS_LOSS_TRANSIENT", "d");
        // Pause playback
        pause();
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        mAudioFocused = true;
        if (LOCAL_LOGD)
            log("AUDIOFOCUS_GAIN", "d");
        // Resume playback or unduck
        if (shouldResumeOnAudioFocus()) {
            if (mCurrentPlayerState.equals(STATE_PAUSED)) {
                resume();
            } else {
                //find out which states this is run into from. change shouldResumeOnAudioFocus() accordingly (only resume when paused?)
                if (LOCAL_LOGD)
                    log("Focus gained,  but playback not resumed", "d"); //investigate
            }
        } else {
            if (LOCAL_LOGD)
                log("Focused gained but playback should not try to resume", "d");
            if (mPreset == 0) {

            }

        }
        unduck();

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {

        if (LOCAL_LOGD)
            log("AUDIOFOCUS_LOSS", "d");
        if (mMediaButtonEventReceiverRegistered) {
            if (LOCAL_LOGV)
                log("unregister button receiver", "v");
            mAudioManager.unregisterMediaButtonEventReceiver(
                    new ComponentName(getPackageName(), ReceiverRemoteControl.class.getName()));
            mMediaButtonEventReceiverRegistered = false;
        } else {
            if (LOCAL_LOGV)
                log("button receiver already unregistered", "v");
        }
        //this.abandonAudioFocus(); //already done in stop()->pause()
        // Stop playback
        stop();

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // Lower the volume
        if (LOCAL_LOGV)
            log("AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK", "v");
        duck();
    }

}

From source file:com.aengbee.android.leanback.ui.PlaybackOverlayCustomFragment.java

private void requestAudioFocus() {
    if (mHasAudioFocus) {
        return;//from   w  ww.  j av a 2s .c  om
    }
    int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mHasAudioFocus = true;
    } else {
        pause();
    }
}

From source file:com.wojtechnology.sunami.TheBrain.java

private void registerAudio() {
    if (mHasAudioFocus || !mIsInit) {
        return;//  w  w  w.j a v  a2 s .c o m
    }
    mHasAudioFocus = true;

    // Add audio focus change listener
    mAFChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                pausePlayback();
                setUI(false);
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Does nothing cause made me play music at work
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                pausePlayback();
                unregisterAudio();
                setUI(false);
            }
        }
    };

    mAudioManager.requestAudioFocus(mAFChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Add headphone out listener
    registerReceiver(mNoisyAudioStreamReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));

    // Add notification and transport controls
    ComponentName eventReceiver = new ComponentName(getPackageName(),
            RemoteControlEventReceiver.class.getName());
    mSession = new MediaSessionCompat(this, "FireSession", eventReceiver, null);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
    mSession.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    mSession.setMetadata(new MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_TITLE, "")
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, "")
            .putLong(MediaMetadata.METADATA_KEY_DURATION, -1).build());

    mSession.setCallback(new MediaSessionCompat.Callback() {

        @Override
        public void onSeekTo(long pos) {
            super.onSeekTo(pos);
            setProgress((int) pos, isPlaying());
        }
    });
    mSession.setActive(true);
}

From source file:com.example.android.leanback.MediaSessionService.java

private void play() {
    // Only when player is not null (meaning the player has been created), the player is
    // prepared (using the mInitialized as the flag to represent it,
    // this boolean variable will only be assigned to true inside of the onPrepared callback)
    // and the media item is not currently playing (!isPlaying()), then the player can be
    // started.//from w  w w.j  av  a 2 s . c om

    // If the player has not been prepared, but this function is fired, it is an error state
    // from the app side
    if (!mInitialized) {
        PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(PlaybackStateCompat.STATE_ERROR);
        builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, PLAYER_NOT_INITIALIZED);
        mMediaSession.setPlaybackState(builder.build());

        // If the player has is playing, and this function is fired again, it is an error state
        // from the app side
    } else {
        // Request audio focus only when needed
        if (mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            return;
        }

        if (mPlayer.getPlaybackParams().getSpeed() != NORMAL_SPEED) {
            // Reset to normal speed and play
            resetSpeedAndPlay();
        } else {
            // Continue play.
            mPlayer.start();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PLAYING).build());
        }
    }

}

From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void registerRemoteControlClient(ComponentName componentName) {

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

    Intent remoteControlIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    remoteControlIntent.setComponent(componentName);

    RemoteControlClient localRemoteControlClient = new RemoteControlClient(
            PendingIntent.getBroadcast(context, 0, remoteControlIntent, 0));

    localRemoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE);

    audioManager.registerRemoteControlClient(localRemoteControlClient);

    this.remoteControlClient = localRemoteControlClient;
}

From source file:com.mine.psf.PsfPlaybackService.java

private void requestAudioFocus() {
    // Request audio focus for playback
    int result = PsfAudioManager.requestAudioFocus(AudioFocusChangeListener,
            // Use the music stream.
            AudioManager.STREAM_MUSIC,/*w  ww.  j  av a 2s  .c  om*/
            // Request permanent focus.
            AudioManager.AUDIOFOCUS_GAIN);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d(LOGTAG, "Audio focus granted");
    } else {
        Log.w(LOGTAG, "Audio focus not granted: " + result);
    }
}

From source file:org.mariotaku.harmony.MusicPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *//*from w w w  .  jav  a 2s .c o m*/
public void play() {
    final TrackInfo track = getTrackInfo();
    if (track == null)
        return;

    if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)
        return;

    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        long duration = mPlayer.getDuration();
        if (mRepeatMode != REPEAT_MODE_CURRENT && duration > 2000 && mPlayer.getPosition() >= duration - 2000) {
            next(true);
        }

        mPlayer.start();

        // make sure we fade in, in case a previous fadein was stopped
        // because
        // of another focus loss
        mMediaplayerHandler.removeMessages(FADEDOWN);
        mMediaplayerHandler.sendEmptyMessage(FADEUP);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        final NotificationCompat.Style style = new NotificationCompat.BigPictureStyle();
        builder.setSmallIcon(R.drawable.ic_stat_playback);
        builder.setContentTitle(track.title);
        if (!TrackInfo.isUnknownArtist(track)) {
            builder.setContentText(track.artist);
        } else if (!TrackInfo.isUnknownAlbum(track)) {
            builder.setContentText(track.album);
        } else {
            builder.setContentText(getString(R.string.unknown_artist));
        }
        final AlbumInfo album = AlbumInfo.getAlbumInfo(this, track);
        builder.setLargeIcon(getAlbumArtForNotification(album != null ? album.album_art : null));
        builder.setStyle(style);
        builder.setOngoing(true);
        builder.setOnlyAlertOnce(true);
        builder.setWhen(0);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(INTENT_PLAYBACK_VIEWER), 0));

        startForeground(ID_NOTIFICATION_PLAYBACK, builder.getNotification());

        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(BROADCAST_PLAY_STATE_CHANGED);
        }

    } else if (mPlayListLen <= 0) {
        // This is mostly so that if you press 'play' on a bluetooth headset
        // without every having played anything before, it will still play
        // something.
        setShuffleMode(SHUFFLE_MODE_ALL);
    }
}

From source file:com.android.tv.MainActivity.java

@Override
protected void onResume() {
    if (DEBUG)/*from   www. java 2  s . c  o m*/
        Log.d(TAG, "onResume()");
    super.onResume();
    if (!PermissionUtils.hasAccessAllEpg(this)
            && checkSelfPermission(PERMISSION_READ_TV_LISTINGS) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] { PERMISSION_READ_TV_LISTINGS }, PERMISSIONS_REQUEST_READ_TV_LISTINGS);
    }
    mTracker.sendScreenView(SCREEN_NAME);

    SystemProperties.updateSystemProperties();
    mNeedShowBackKeyGuide = true;
    mActivityResumed = true;
    mShowNewSourcesFragment = true;
    mOtherActivityLaunched = false;
    int result = mAudioManager.requestAudioFocus(MainActivity.this, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioFocusStatus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) ? AudioManager.AUDIOFOCUS_GAIN
            : AudioManager.AUDIOFOCUS_LOSS;
    setVolumeByAudioFocusStatus();

    if (mTvView.isPlaying()) {
        // Every time onResume() is called the activity will be assumed to not have requested
        // visible behind.
        requestVisibleBehind(true);
    }
    if (mChannelTuner.areAllChannelsLoaded()) {
        SetupUtils.getInstance(this).markNewChannelsBrowsable();
        resumeTvIfNeeded();
        resumePipIfNeeded();
    }
    mOverlayManager.showMenuWithTimeShiftPauseIfNeeded();

    // Note: The following codes are related to pop up an overlay UI after resume.
    // When the following code is changed, please check the variable
    // willShowOverlayUiAfterResume in updateChannelBannerAndShowIfNeeded.
    if (mInputToSetUp != null) {
        startSetupActivity(mInputToSetUp, false);
        mInputToSetUp = null;
    } else if (mShowProgramGuide) {
        mShowProgramGuide = false;
        mHandler.post(new Runnable() {
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showProgramGuide();
            }
        });
    } else if (mShowSelectInputView) {
        mShowSelectInputView = false;
        mHandler.post(new Runnable() {
            // mShowSelectInputView is true when the activity is started/resumed because the
            // TV_INPUT button was pressed in a different app.
            // This will delay the start of the animation until after the Live Channel app is
            // shown. Without this the animation is completed before it is actually visible on
            // the screen.
            @Override
            public void run() {
                mOverlayManager.showSelectInputView();
            }
        });
    }
}

From source file:mp.teardrop.PlaybackService.java

private void processNewState(int oldState, int state) {
    int toggled = oldState ^ state;

    if ((toggled & FLAG_PLAYING) != 0) {
        if ((state & FLAG_PLAYING) != 0) {
            if (mMediaPlayerInitialized)
                mMediaPlayer.start();/*from   w  w  w  .j a  v  a  2s  .c  o m*/

            if (mNotificationMode != NEVER)
                startForeground(NOTIFICATION_ID, createNotification(mCurrentSong, mState));

            mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

            mHandler.removeMessages(RELEASE_WAKE_LOCK);
            try {
                if (mWakeLock != null && mWakeLock.isHeld() == false)
                    mWakeLock.acquire();
            } catch (SecurityException e) {
                // Don't have WAKE_LOCK permission
            }
        } else {
            if (mMediaPlayerInitialized)
                mMediaPlayer.pause();

            if (mNotificationMode == ALWAYS || mForceNotificationVisible) {
                stopForeground(false);
                mNotificationManager.notify(NOTIFICATION_ID, createNotification(mCurrentSong, mState));
            } else {
                stopForeground(true);
            }

            // Delay release of the wake lock. This allows the headset
            // button to continue to function for a short period after
            // pausing.
            mHandler.sendEmptyMessageDelayed(RELEASE_WAKE_LOCK, WAKE_LOCK_DELAY);
        }

        setupSensor();
    }

    if ((toggled & FLAG_NO_MEDIA) != 0 && (state & FLAG_NO_MEDIA) != 0) {
        Song song = mCurrentSong;
        if (song != null && mMediaPlayerInitialized) {
            mPendingSeek = mMediaPlayer.getCurrentPosition();
            mPendingSeekSong = song.id;
        }
    }

    if ((toggled & MASK_SHUFFLE) != 0)
        mTimeline.setShuffleMode(shuffleMode(state));
    if ((toggled & MASK_FINISH) != 0)
        mTimeline.setFinishAction(finishAction(state));

    triggerGaplessUpdate();
    triggerReadAhead();
}