Example usage for android.support.v4.media.session PlaybackStateCompat STATE_PAUSED

List of usage examples for android.support.v4.media.session PlaybackStateCompat STATE_PAUSED

Introduction

In this page you can find the example usage for android.support.v4.media.session PlaybackStateCompat STATE_PAUSED.

Prototype

int STATE_PAUSED

To view the source code for android.support.v4.media.session PlaybackStateCompat STATE_PAUSED.

Click Source Link

Document

State indicating this item is currently paused.

Usage

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

/**
 * Control the player to play next music item.
 * Expected Interaction Behavior://from w ww.  ja v a  2s .  co m
 * No matter current media item is playing or not, when use hit next button, next item will be
 * prepared but won't play unless user hit play button
 *
 * Also no matter current media item is fast forwarding or rewinding. Next music item will
 * be played in normal speed.
 */
private void next() {
    if (mMediaItemList.isEmpty()) {
        return;
    }
    mCurrentIndex = (mCurrentIndex + 1) % mMediaItemList.size();
    mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);

    // Reset FastForward/ Rewind state to normal state
    mFastForwardSpeedFactorIndex = 0;
    mRewindSpeedFactorIndex = 0;
    // Set player's playback speed back to normal
    mPlayer.setPlaybackParams(
            mPlayer.getPlaybackParams().setSpeed(mFastForwardSpeedFactors[mFastForwardSpeedFactorIndex]));
    // Pause the player and update the play state.
    // The ui will also be changed from "playing" state to "pause" state.
    mPlayer.pause();
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
    // set new data source to play based on mCurrentIndex and prepare the player.
    // The ui will also be changed from "playing" state to "pause" state through setDataSource()
    // operation
    setDataSource();
}

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

/**
 * Control the player to play next music item.
 * Expected Interaction Behavior://from   w  ww.  ja v  a2  s .  c o m
 * No matter current media item is playing or not, when use hit previous button, previous item
 * will be prepared but won't play unless user hit play button
 *
 * Also no matter current media item is fast forwarding or rewinding. Previous music item will
 * be played in normal speed.
 */
private void previous() {
    if (mMediaItemList.isEmpty()) {
        return;
    }
    mCurrentIndex = (mCurrentIndex - 1 + mMediaItemList.size()) % mMediaItemList.size();
    mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);

    // Reset FastForward/ Rewind state to normal state
    mFastForwardSpeedFactorIndex = 0;
    mRewindSpeedFactorIndex = 0;
    // Set player's playback speed back to normal
    mPlayer.setPlaybackParams(
            mPlayer.getPlaybackParams().setSpeed(mFastForwardSpeedFactors[mFastForwardSpeedFactorIndex]));
    // Pause the player and update the play state.
    // The ui will also be changed from "playing" state to "pause" state.
    mPlayer.pause();
    // Update playbackState.
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
    // set new data source to play based on mCurrentIndex and prepare the player.
    // The ui will also be changed from "playing" state to "pause" state through setDataSource()
    // operation
    setDataSource();
}

From source file:com.torrenttunes.android.MusicService.java

/**
 * Update the current media player state, optionally showing an error message.
 *
 * @param error if not null, error message to present to the user.
 *//*from w  ww .  java  2s.c  o m*/
private void updatePlaybackState(String error) {
    LogHelper.d(TAG, "updatePlaybackState, playback state=" + mPlayback.getState());
    long position = PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN;
    if (mPlayback != null && mPlayback.isConnected()) {
        position = mPlayback.getCurrentStreamPosition();
    }

    PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder()
            .setActions(getAvailableActions());

    setCustomAction(stateBuilder);
    int state = mPlayback.getState();

    // If there is an error message, send it to the playback state:
    if (error != null) {
        // Error states are really only supposed to be used for errors that cause playback to
        // stop unexpectedly and persist until the user takes action to fix it.
        stateBuilder.setErrorMessage(error);
        state = PlaybackStateCompat.STATE_ERROR;
    }
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    // Set the activeQueueItemId if the current index is valid.
    if (QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
        MediaSessionCompat.QueueItem item = mPlayingQueue.get(mCurrentIndexOnQueue);
        //            stateBuilder.setActiveQueueItemId(item.getQueueId());
    }

    mSession.setPlaybackState(stateBuilder.build());

    if (state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_PAUSED) {
        mMediaNotificationManager.startNotification();
    }
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

@Override
public void onDestroy() {
    super.onDestroy();

    EventBus.getDefault().unregister(this);

    giveUpAudioFocus();//from  w  w  w .  j  av a2 s.com

    mPlaybackManager.setCallback(null);

    if (mAudioBecomingNoisyReceiver != null) {
        unregisterReceiver(mAudioBecomingNoisyReceiver);
        mAudioBecomingNoisyReceiver = null;
    }
    mScrobbleHandler.stop();

    mPlayState = PlaybackStateCompat.STATE_PAUSED;
    handlePlayState();
    mNotification.stopNotification();

    releaseAllPlayers();
    if (mWakeLock.isHeld()) {
        mWakeLock.release();
    }
    mWakeLock = null;
    mSuicideHandler.stop();
    mSuicideHandler = null;
    mPluginServiceKillHandler.stop();
    mPluginServiceKillHandler = null;
    if (mMediaSession != null) {
        mMediaSession.setCallback(null);
        mMediaSession.release();
        mMediaSession = null;
    }

    if (mRemoteControllerConnection != null) {
        unbindService(mRemoteControllerConnection);
    }
    unbindPluginServices();

    Log.d(TAG, "PlaybackService has been destroyed");
}

From source file:com.torrenttunes.android.MusicService.java

/**
 * Helper to switch to a different Playback instance
 * @param playback switch to this playback
 *//*  www  . j  av  a 2s  .  c o  m*/
private void switchToPlayer(Playback playback, boolean resumePlaying) {
    if (playback == null) {
        throw new IllegalArgumentException("Playback cannot be null");
    }
    // suspend the current one.
    int oldState = mPlayback.getState();
    int pos = mPlayback.getCurrentStreamPosition();
    String currentMediaId = mPlayback.getCurrentMediaId();
    LogHelper.d(TAG, "Current position from " + playback + " is ", pos);
    mPlayback.stop(false);
    playback.setCallback(this);
    playback.setCurrentStreamPosition(pos < 0 ? 0 : pos);
    playback.setCurrentMediaId(currentMediaId);
    playback.start();
    // finally swap the instance
    mPlayback = playback;
    switch (oldState) {
    case PlaybackStateCompat.STATE_BUFFERING:
    case PlaybackStateCompat.STATE_CONNECTING:
    case PlaybackStateCompat.STATE_PAUSED:
        mPlayback.pause();
        break;
    case PlaybackStateCompat.STATE_PLAYING:
        if (resumePlaying && QueueHelper.isIndexPlayable(mCurrentIndexOnQueue, mPlayingQueue)) {
            mPlayback.play(mPlayingQueue.get(mCurrentIndexOnQueue));
        } else if (!resumePlaying) {
            mPlayback.pause();
        } else {
            mPlayback.stop(true);
        }
        break;
    case PlaybackStateCompat.STATE_NONE:
        break;
    default:
        LogHelper.d(TAG, "Default called. Old state is ", oldState);
    }
}

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

protected void publishState(int state) {
    if (mMediaSession == null)
        return;//from  w ww  .j  a va 2 s  .c  om
    PlaybackStateCompat.Builder bob = new PlaybackStateCompat.Builder();
    bob.setActions(PLAYBACK_ACTIONS);
    switch (state) {
    case MediaPlayer.Event.Playing:
        bob.setState(PlaybackStateCompat.STATE_PLAYING, getCurrentMediaPosition(), getRate());
        break;
    case MediaPlayer.Event.Stopped:
        bob.setState(PlaybackStateCompat.STATE_STOPPED, getCurrentMediaPosition(), getRate());
        break;
    default:
        bob.setState(PlaybackStateCompat.STATE_PAUSED, getCurrentMediaPosition(), getRate());
    }
    PlaybackStateCompat pbState = bob.build();
    mMediaSession.setPlaybackState(pbState);
    mMediaSession.setActive(state != PlaybackStateCompat.STATE_STOPPED);
}

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

private void audioFocusLossHandler() {
    // Permanent loss of audio focus
    // Pause playback immediately
    mPlayer.pause();/*from   ww  w.j  a v  a2 s .  co m*/
    // Wait 30 seconds before stopping playback
    mMediaPlayerHandler.postDelayed(mDelayedStopRunnable, 30);
    // Update playback state.
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
    // Will record current player progress when losing the audio focus.
    mCurrentPosition = getCurrentPosition();
}

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

private void audioLossFocusTransientHandler() {
    // In this case, we already have lost the audio focus, and we cannot duck.
    // So the player will be paused immediately, but different with the previous state, there is
    // no need to stop the player.
    mPlayer.pause();/*from ww w  . ja v a 2  s  .  c o m*/
    // update playback state
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
    // Will record current player progress when lossing the audio focus.
    mCurrentPosition = getCurrentPosition();
}

From source file:com.techmighty.baseplayer.MusicService.java

private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying ? PlaybackStateCompat.STATE_PLAYING
            : PlaybackStateCompat.STATE_PAUSED;

    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());//from   w w w .  j  a va 2  s. co  m
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = ImageLoader.getInstance()
                .loadImageSync(BasePlayerUtils.getAlbumArtUri(getAlbumId()).toString());
        if (albumArt != null) {

            Bitmap.Config config = albumArt.getConfig();
            if (config == null) {
                config = Bitmap.Config.ARGB_8888;
            }
            albumArt = albumArt.copy(config, false);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName())
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName())
                    .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration())
                    .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1)
                    .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length)
                    .putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
                            mShowAlbumArtOnLockscreen ? albumArt : null)
                    .build());

            mSession.setPlaybackState(new PlaybackStateCompat.Builder().setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                            | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    }
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

/**
 * Update the TomahawkMediaPlayer so that it reflects the current playState
 *///from w  ww  .  j av a  2  s  . com
private void handlePlayState() {
    Log.d(TAG, "handlePlayState");
    final Query currentQuery = mPlaybackManager.getCurrentQuery();
    if (currentQuery != null && currentQuery.getMediaPlayerClass() != null) {
        final TomahawkMediaPlayer mp = mMediaPlayers.get(currentQuery.getMediaPlayerClass());
        Runnable r = new Runnable() {
            @Override
            public void run() {
                switch (mPlayState) {
                case PlaybackStateCompat.STATE_PLAYING:
                    // The service needs to continue running even after the bound client
                    // (usually a MediaController) disconnects, otherwise the music playback
                    // will stop. Calling startService(Intent) will keep the service running
                    // until it is explicitly killed.
                    startService(new Intent(getApplicationContext(), PlaybackService.class));
                    if (mWakeLock != null && mWakeLock.isHeld()) {
                        mWakeLock.acquire();
                    }
                    if (mp.isPreparing(currentQuery) || mp.isPrepared(currentQuery)) {
                        if (!mp.isPlaying(currentQuery)) {
                            mp.play();
                        }
                    } else {
                        prepareCurrentQuery();
                    }
                    break;
                case PlaybackStateCompat.STATE_PAUSED:
                    if (mp.isPlaying(currentQuery)
                            && (mp.isPreparing(currentQuery) || mp.isPrepared(currentQuery))) {
                        InfoSystem.get().sendPlaybackEntryPostStruct(AuthenticatorManager.get()
                                .getAuthenticatorUtils(TomahawkApp.PLUGINNAME_HATCHET));
                        mp.pause();
                    }
                    if (mWakeLock != null && mWakeLock.isHeld()) {
                        mWakeLock.release();
                    }
                    break;
                }
            }
        };
        ThreadManager.get().executePlayback(mp, r);
    } else {
        releaseAllPlayers();
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mWakeLock.release();
        }
        Log.d(TAG, "handlePlayState couldn't do anything, isPreparing: " + mIsPreparing);
    }
}