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

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

Introduction

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

Prototype

int STATE_ERROR

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

Click Source Link

Document

State indicating this item is currently in an error state.

Usage

From source file:com.murati.oszk.audiobook.ui.MediaItemViewHolder.java

public static int getStateFromController(Activity context) {
    MediaControllerCompat controller = MediaControllerCompat.getMediaController(context);
    PlaybackStateCompat pbState = controller.getPlaybackState();
    if (pbState == null || pbState.getState() == PlaybackStateCompat.STATE_ERROR) {
        return MediaItemViewHolder.STATE_NONE;
    } else if (pbState.getState() == PlaybackStateCompat.STATE_PLAYING) {
        return MediaItemViewHolder.STATE_PLAYING;
    } else {/*ww  w. ja  v  a 2 s  .  c  o  m*/
        return MediaItemViewHolder.STATE_PAUSED;
    }
}

From source file:net.simno.klingar.playback.LocalPlayback.java

@Override
public void onPlayerError(ExoPlaybackException error) {
    Timber.e(error, "Exception playing song");
    state = PlaybackStateCompat.STATE_ERROR;
    if (callback != null) {
        callback.onPlaybackStatusChanged();
    }/*from www .  ja v a2s. co m*/
}

From source file:cat.terrones.devops.radiofx.ui.MediaBrowserFragment.java

private void checkForUserVisibleErrors(boolean forceError) {
    boolean showError = forceError;
    // If offline, message is about the lack of connectivity:
    if (!Utils.isOnline(getActivity())) {
        mErrorMessage.setText(R.string.error_no_connection);
        showError = true;//from  ww  w .j  av a 2 s  .c o  m
    } else {
        // otherwise, if state is ERROR and metadata!=null, use playback state error message:
        MediaControllerCompat controller = ((FragmentActivity) getActivity()).getSupportMediaController();
        if (controller != null && controller.getMetadata() != null && controller.getPlaybackState() != null
                && controller.getPlaybackState().getState() == PlaybackStateCompat.STATE_ERROR
                && controller.getPlaybackState().getErrorMessage() != null) {
            mErrorMessage.setText(controller.getPlaybackState().getErrorMessage());
            showError = true;
        } else if (forceError) {
            // Finally, if the caller requested to show error, show a generic message:
            mErrorMessage.setText(R.string.error_loading_media);
            showError = true;
        }
    }
    mErrorView.setVisibility(showError ? View.VISIBLE : View.GONE);
    Log.d(TAG, "checkForUserVisibleErrors. forceError=" + forceError + " showError=" + showError + " isOnline="
            + Utils.isOnline(getActivity()));
}

From source file:rocks.stalin.android.app.ui.MediaBrowserFragment.java

private void checkForUserVisibleErrors(boolean forceError) {
    boolean showError = forceError;
    // If offline, message is about the lack of connectivity:
    if (!NetworkHelper.isOnline(getActivity())) {
        mErrorMessage.setText(R.string.error_no_connection);
        showError = true;//from   www  . jav  a 2  s  . c  om
    } else {
        // otherwise, if state is ERROR and metadata!=null, use playback state error message:
        MediaControllerCompat controller = MediaControllerCompat.getMediaController(getActivity());
        if (controller != null && controller.getMetadata() != null && controller.getPlaybackState() != null
                && controller.getPlaybackState().getState() == PlaybackStateCompat.STATE_ERROR
                && controller.getPlaybackState().getErrorMessage() != null) {
            mErrorMessage.setText(controller.getPlaybackState().getErrorMessage());
            showError = true;
        } else if (forceError) {
            // Finally, if the caller requested to show error, show a generic message:
            mErrorMessage.setText(R.string.error_loading_media);
            showError = true;
            PermissionHelper.requestMissingPermissions(getActivity(),
                    PermissionHelper.SHOULD_RECREATE_ACTIVITY);
        }
    }
    mErrorView.setVisibility(showError ? View.VISIBLE : View.GONE);
    LogHelper.d(TAG, "checkForUserVisibleErrors. forceError=", forceError, " showError=", showError,
            " isOnline=", NetworkHelper.isOnline(getActivity()));
}

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  .ja va 2  s.  com*/
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.murati.oszk.audiobook.ui.MediaBrowserFragment.java

private void checkForUserVisibleErrors(boolean forceError) {
    boolean showError = forceError;
    // If offline, message is about the lack of connectivity:
    if (!NetworkHelper.isOnline(getActivity())) {
        mErrorMessage.setText(R.string.notification_offline);
        showError = true;/* w  w  w .  j a v  a  2  s.c  om*/
    } else {
        // otherwise, if state is ERROR and metadata!=null, use playback state error message:
        MediaControllerCompat controller = MediaControllerCompat.getMediaController(getActivity());
        if (controller != null && controller.getMetadata() != null && controller.getPlaybackState() != null
                && controller.getPlaybackState().getState() == PlaybackStateCompat.STATE_ERROR
                && controller.getPlaybackState().getErrorMessage() != null) {
            mErrorMessage.setText(controller.getPlaybackState().getErrorMessage());
            showError = true;
        } else if (forceError) {
            // Finally, if the caller requested to show error, show a generic message:
            mErrorMessage.setText(R.string.error_loading_media);
            showError = true;
        }
    }
    mErrorView.setVisibility(showError ? View.VISIBLE : View.GONE);
    LogHelper.d(TAG, "checkForUserVisibleErrors. forceError=", forceError, " showError=", showError,
            " isOnline=", NetworkHelper.isOnline(getActivity()));
}

From source file:androidx.media.MediaUtils2.java

static int createPlaybackStateCompatState(int playerState, int bufferingState) {
    switch (playerState) {
    case MediaPlayerBase.PLAYER_STATE_PLAYING:
        switch (bufferingState) {
        case MediaPlayerBase.BUFFERING_STATE_BUFFERING_AND_STARVED:
            return PlaybackStateCompat.STATE_BUFFERING;
        }//  w w w  .  j  a v a 2  s . c  o m
        return PlaybackStateCompat.STATE_PLAYING;
    case MediaPlayerBase.PLAYER_STATE_PAUSED:
        return PlaybackStateCompat.STATE_PAUSED;
    case MediaPlayerBase.PLAYER_STATE_IDLE:
        return PlaybackStateCompat.STATE_NONE;
    case MediaPlayerBase.PLAYER_STATE_ERROR:
        return PlaybackStateCompat.STATE_ERROR;
    }
    // For unknown value
    return PlaybackStateCompat.STATE_ERROR;
}

From source file:androidx.media.MediaUtils2.java

static int toPlayerState(int playbackStateCompatState) {
    switch (playbackStateCompatState) {
    case PlaybackStateCompat.STATE_ERROR:
        return MediaPlayerBase.PLAYER_STATE_ERROR;
    case PlaybackStateCompat.STATE_NONE:
        return MediaPlayerBase.PLAYER_STATE_IDLE;
    case PlaybackStateCompat.STATE_PAUSED:
    case PlaybackStateCompat.STATE_STOPPED:
    case PlaybackStateCompat.STATE_BUFFERING: // means paused for buffering.
        return MediaPlayerBase.PLAYER_STATE_PAUSED;
    case PlaybackStateCompat.STATE_FAST_FORWARDING:
    case PlaybackStateCompat.STATE_PLAYING:
    case PlaybackStateCompat.STATE_REWINDING:
    case PlaybackStateCompat.STATE_SKIPPING_TO_NEXT:
    case PlaybackStateCompat.STATE_SKIPPING_TO_PREVIOUS:
    case PlaybackStateCompat.STATE_SKIPPING_TO_QUEUE_ITEM:
    case PlaybackStateCompat.STATE_CONNECTING: // Note: there's no perfect match for this.
        return MediaPlayerBase.PLAYER_STATE_PLAYING;
    }//from  w  w  w. j ava2  s .  com
    return MediaPlayerBase.PLAYER_STATE_ERROR;
}

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

/**
 * Prepare the first item in the list. And setup the listener for media player.
 *///ww  w .ja  v 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.scooter1556.sms.lib.android.service.AudioPlayerService.java

public void initialiseTrack(int position) {

    // Get settings
    final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

    // Get media element to play
    final MediaElement mediaElement = mediaElementList.get(position);

    if (mediaElement == null) {
        Toast error = Toast.makeText(getApplicationContext(), getString(R.string.error_media_playback),
                Toast.LENGTH_SHORT);//www  .ja v a  2  s .  c o  m
        error.show();
        return;
    }

    // Initialise Stream
    restService.initialiseStream(getApplicationContext(), mediaElement.getID(), SUPPORTED_FILES,
            SUPPORTED_CODECS, null, null, Integer.parseInt(settings.getString("pref_audio_quality", "0")),
            MAX_SAMPLE_RATE, null, null, settings.getBoolean("pref_direct_play", false),
            new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers,
                        JSONObject response) {
                    // Initialise player
                    player = new SMSAudioPlayer();

                    // Update state
                    mediaState = PlaybackStateCompat.STATE_CONNECTING;
                    updatePlaybackState();

                    // Parse profile
                    Gson parser = new Gson();
                    TranscodeProfile profile = parser.fromJson(response.toString(), TranscodeProfile.class);

                    // Setup Player
                    player.setID(mediaElement.getID());
                    player.setDuration(mediaElement.getDuration());
                    player.setTranscodeProfile(profile);
                    player.setQuality(Integer.parseInt(settings.getString("pref_audio_quality", "0")));

                    // Streaming status
                    if (profile.getType() == TranscodeProfile.StreamType.FILE) {
                        player.setStreaming(false);
                    } else {
                        player.setStreaming(true);
                    }

                    try {
                        preparePlayer();
                        isPaused = false;

                        // Update metadata
                        mediaSession.setMetadata(MediaUtils.getMediaMetadata(mediaElement, null));

                        // Attempt to get album art
                        Glide.with(getApplicationContext())
                                .load(RESTService.getInstance().getConnection().getUrl() + "/image/"
                                        + mediaElement.getID() + "/cover/300")
                                .asBitmap().into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap image,
                                            GlideAnimation<? super Bitmap> glideAnimation) {
                                        // Update metadata with artwork
                                        mediaSession
                                                .setMetadata(MediaUtils.getMediaMetadata(mediaElement, image));
                                    }
                                });

                        // Update listeners
                        for (AudioPlayerListener listener : listeners) {
                            listener.PlaybackStateChanged();
                            listener.PlaylistPositionChanged();
                        }

                    } catch (Exception e) {
                        cleanupPlayer();
                    }
                }

                @Override
                public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers,
                        Throwable throwable, JSONObject response) {
                    error();
                }

                private void error() {
                    Toast error = Toast.makeText(getApplicationContext(),
                            getString(R.string.error_media_playback), Toast.LENGTH_SHORT);
                    error.show();

                    currentListPosition = 0;

                    // Update state
                    mediaState = PlaybackStateCompat.STATE_ERROR;
                    updatePlaybackState();

                    // Update listeners
                    for (AudioPlayerListener listener : listeners) {
                        listener.PlaybackStateChanged();
                        listener.PlaylistPositionChanged();
                    }
                }
            });
}