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

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

Introduction

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

Prototype

int ERROR_CODE_APP_ERROR

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

Click Source Link

Document

Error code when the application state is invalid to fulfill the request.

Usage

From source file:com.doctoror.fuckoffmusicplayer.data.reporter.MediaSessionPlaybackReporter.java

@Override
public void reportPlaybackStateChanged(@NonNull final PlaybackState state,
        @Nullable final CharSequence errorMessage) {
    @PlaybackStateCompat.State//from   www .  j a  v a2 s.c om
    final int playbackState = toPlaybackStateCompat(state);
    final boolean isPlaying = playbackState == PlaybackStateCompat.STATE_PLAYING;
    final PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE
                    | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
                    | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH)
            .setState(playbackState, 0, isPlaying ? 1 : 0);

    if (errorMessage != null) {
        builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, errorMessage);
    }

    mMediaSession.setPlaybackState(builder.build());
}

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

/**
 * After binding to this service, other component can set Media Item List and prepare
 * the first item in the list through this function.
 *
 * @param mediaItemList A list of media item to play.
 * @param isQueue       When this parameter is true, that meas new items should be appended to
 *                      original media item list.
 *                      If this parameter is false, the original playlist will be cleared and
 *                      replaced with a new media item list.
 *//*w ww  . j a  v a2  s . co  m*/
public void setMediaList(List<MusicItem> mediaItemList, boolean isQueue) {
    if (!isQueue) {
        mMediaItemList.clear();
    }
    mMediaItemList.addAll(mediaItemList);

    /**
     * Points to the first media item in play list.
     */
    mCurrentIndex = 0;
    mCurrentMediaItem = mMediaItemList.get(0);

    try {
        mPlayer.setDataSource(this.getApplicationContext(),
                mCurrentMediaItem.getMediaSourceUri(getApplicationContext()));
        // Prepare the player asynchronously, use onPrepared listener as signal.
        mPlayer.prepareAsync();
    } catch (IOException e) {
        PlaybackStateCompat.Builder ret = createPlaybackStateBuilder(PlaybackStateCompat.STATE_ERROR);
        ret.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, PLAYER_SET_DATA_SOURCE_ERROR);
    }
}

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

/**
 * Prepare the first item in the list. And setup the listener for media player.
 *///from  ww  w  .j  av a  2s . c o  m
private void initializePlayer() {
    // This service can be created for multiple times, the objects will only be created when
    // it is null
    if (mPlayer != null) {
        return;
    }
    mPlayer = new MediaPlayer();

    // Set playback state to none to create a valid playback state. So controls row can get
    // information about the supported actions.
    mMediaSession.setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_NONE).build());
    // Activate media session
    if (!mMediaSession.isActive()) {
        mMediaSession.setActive(true);
    }

    // Set up listener and audio stream type for underlying music player.
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    // set up listener when the player is prepared.
    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mInitialized = true;
            // Every time when the player is prepared (when new data source is set),
            // all listeners will be notified to toggle the UI to "pause" status.
            notifyUiWhenPlayerIsPrepared();

            // When media player is prepared, the callback functions will be executed to update
            // the meta data and playback state.
            onMediaSessionMetaDataChanged();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());
        }
    });

    // set up listener for player's error.
    mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            if (DEBUG) {
                PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(
                        PlaybackStateCompat.STATE_ERROR);
                builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, MEDIA_PLAYER_ERROR_MESSAGE);
                mMediaSession.setPlaybackState(builder.build());
            }
            return true;
        }
    });

    // set up listener to respond the event when current music item is finished
    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        /**
         * Expected Interaction Behavior:
         * 1. If current media item's playing speed not equal to normal speed.
         *
         *    A. MEDIA_ACTION_REPEAT_ALL
         *       a. If current media item is the last one. The first music item in the list will
         *          be prepared, but it won't play until user press play button.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         *       b. If current media item isn't the last one, next media item will be prepared,
         *          but it won't play.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         *    B. MEDIA_ACTION_REPEAT_ONE
         *       Different with previous scenario, current item will go back to the start point
         *       again and play automatically. (The reason to enable auto play here is for
         *       testing purpose and to make sure our designed API is flexible enough to support
         *       different situations.)
         *
         *       No matter what the previous media item's playing speed is, in this situation
         *       current media item will be replayed in normal speed.
         *
         *    C. MEDIA_ACTION_REPEAT_NONE
         *       a. If current media is the last one. The service will be closed, no music item
         *          will be prepared to play. From the UI perspective, the progress bar will not
         *          be reset to the starting point.
         *
         *       b. If current media item isn't the last one, next media item will be prepared,
         *          but it won't play.
         *
         *          When user press the play button, the speed will be reset to normal (1.0f)
         *          no matter what the previous media item's playing speed is.
         *
         * @param mp Object of MediaPlayer
         */
        @Override
        public void onCompletion(MediaPlayer mp) {

            // When current media item finishes playing, always reset rewind/ fastforward 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 status accordingly.
            mPlayer.pause();
            mMediaSession
                    .setPlaybackState(createPlaybackStateBuilder(PlaybackStateCompat.STATE_PAUSED).build());

            if (mRepeatState == MEDIA_ACTION_REPEAT_ALL && mCurrentIndex == mMediaItemList.size() - 1) {
                // if the repeat mode is enabled but the shuffle mode is not enabled,
                // will go back to the first music item to play
                if (mShuffleMode == PlaybackStateCompat.SHUFFLE_MODE_NONE) {
                    mCurrentIndex = 0;
                } else {
                    // Or will choose a music item from playing list randomly.
                    mCurrentIndex = generateMediaItemIndex();
                }
                mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);
                // The ui will also be changed from playing state to pause state through
                // setDataSource() operation
                setDataSource();
            } else if (mRepeatState == MEDIA_ACTION_REPEAT_ONE) {
                // Play current music item again.
                // The ui will stay to be "playing" status for the reason that there is no
                // setDataSource() function call.
                mPlayer.start();
                mMediaSession.setPlaybackState(
                        createPlaybackStateBuilder(PlaybackStateCompat.STATE_PLAYING).build());
            } else if (mCurrentIndex < mMediaItemList.size() - 1) {
                if (mShuffleMode == PlaybackStateCompat.SHUFFLE_MODE_NONE) {
                    mCurrentIndex++;
                } else {
                    mCurrentIndex = generateMediaItemIndex();
                }
                mCurrentMediaItem = mMediaItemList.get(mCurrentIndex);
                // The ui will also be changed from playing state to pause state through
                // setDataSource() operation
                setDataSource();
            } else {
                // close the service when the playlist is finished
                // The PlaybackState will be updated to STATE_STOPPED. And onPlayComplete
                // callback will be called by attached glue.
                mMediaSession.setPlaybackState(
                        createPlaybackStateBuilder(PlaybackStateCompat.STATE_STOPPED).build());
                stopSelf();
            }
        }
    });

    final MediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            mBufferedProgress = getDuration() * percent / 100;
            PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(
                    PlaybackStateCompat.STATE_BUFFERING);
            builder.setBufferedPosition(mBufferedProgress);
            mMediaSession.setPlaybackState(builder.build());
        }
    };
    mPlayer.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
}

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

/**
 * Set new data source and prepare the music player asynchronously.
 *///w  w  w .ja v a 2 s .  c o m
private void setDataSource() {
    reset();
    try {
        mPlayer.setDataSource(this.getApplicationContext(),
                mCurrentMediaItem.getMediaSourceUri(getApplicationContext()));
        mPlayer.prepareAsync();
    } catch (IOException e) {
        PlaybackStateCompat.Builder builder = createPlaybackStateBuilder(PlaybackStateCompat.STATE_ERROR);
        builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, CANNOT_SET_DATA_SOURCE);
        mMediaSession.setPlaybackState(builder.build());
    }
}

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 www  .  j  av a 2 s  .co m

    // 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());
        }
    }

}