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

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

Introduction

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

Prototype

int STATE_PLAYING

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

Click Source Link

Document

State indicating this item is currently playing.

Usage

From source file:rocks.stalin.android.app.playback.PlaybackManager.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 ww  w.  j a  v a 2  s . co  m
public 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();
    }

    //noinspection ResourceType
    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(PlaybackStateCompat.ERROR_CODE_UNKNOWN_ERROR, error);
        state = PlaybackStateCompat.STATE_ERROR;
    }
    //noinspection ResourceType
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    // Set the activeQueueItemId if the current index is valid.
    MediaSessionCompat.QueueItem currentMusic = mQueueManager.getCurrentMusic();
    if (currentMusic != null) {
        stateBuilder.setActiveQueueItemId(currentMusic.getQueueId());
    }

    mServiceCallback.onPlaybackStateUpdated(stateBuilder.build());

    if (state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_PAUSED) {
        mServiceCallback.onNotificationRequired();
    }
}

From source file:com.murati.oszk.audiobook.playback.PlaybackManager.java

/**
 * Update the current media player state, optionally showing an error message.
 *
 * @param error if not null, error message to present to the user.
 */// w  w w.j  a v a 2  s  . co  m
public 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();
    }

    //noinspection ResourceType
    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;
    }
    //noinspection ResourceType
    stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());

    // Set the activeQueueItemId if the current index is valid.
    MediaSessionCompat.QueueItem currentMusic = mQueueManager.getCurrentTrack();
    if (currentMusic != null) {
        stateBuilder.setActiveQueueItemId(currentMusic.getQueueId());
    }

    mServiceCallback.onPlaybackStateUpdated(stateBuilder.build());

    if (state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_PAUSED) {
        mServiceCallback.onNotificationRequired();
    }
}

From source file:org.runbuddy.tomahawk.ui.fragments.PlaylistEntriesFragment.java

/**
 * Called every time an item inside a ListView or GridView is clicked
 *
 * @param view    the clicked view/*  ww w.j  a  v a2s .  c om*/
 * @param item    the Object which corresponds to the click
 * @param segment
 */
@Override
public void onItemClick(View view, Object item, Segment segment) {
    if (getMediaController() == null) {
        Log.e(TAG, "onItemClick failed because getMediaController() is null");
        return;
    }
    if (item instanceof PlaylistEntry) {
        PlaylistEntry entry = (PlaylistEntry) item;
        if (entry.getQuery().isPlayable()) {
            if (getPlaybackManager().getCurrentEntry() == entry) {
                // if the user clicked on an already playing track
                int playState = getMediaController().getPlaybackState().getState();
                if (playState == PlaybackStateCompat.STATE_PLAYING) {
                    getMediaController().getTransportControls().pause();
                } else if (playState == PlaybackStateCompat.STATE_PAUSED) {
                    getMediaController().getTransportControls().play();
                }
            } else {
                getPlaybackManager().setPlaylist(mCurrentPlaylist, entry);
                getMediaController().getTransportControls().play();
            }
        }
    }
}

From source file:com.example.android.AudioArchive.ui.FullScreenPlayerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_full_player);
    initializeToolbar();/*from   ww  w .  jav a  2 s. com*/
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("");
    }

    mBackgroundImage = (ImageView) findViewById(R.id.background_image);
    mPauseDrawable = ContextCompat.getDrawable(this, R.drawable.uamp_ic_pause_white_48dp);
    mPlayDrawable = ContextCompat.getDrawable(this, R.drawable.uamp_ic_play_arrow_white_48dp);
    mPlayPause = (ImageView) findViewById(R.id.play_pause);
    mSkipNext = (ImageView) findViewById(R.id.next);
    mSkipPrev = (ImageView) findViewById(R.id.prev);

    mLine1 = (TextView) findViewById(R.id.line1);
    mLine2 = (TextView) findViewById(R.id.line2);
    mLine3 = (TextView) findViewById(R.id.line3);
    mLoading = (ProgressBar) findViewById(R.id.progressBar1);
    mControllers = findViewById(R.id.controllers);

    mSkipNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MediaControllerCompat.TransportControls controls = getSupportMediaController()
                    .getTransportControls();
            controls.skipToNext();
        }
    });

    mSkipPrev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MediaControllerCompat.TransportControls controls = getSupportMediaController()
                    .getTransportControls();
            controls.skipToPrevious();
        }
    });

    mPlayPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PlaybackStateCompat state = getSupportMediaController().getPlaybackState();
            if (state != null) {
                MediaControllerCompat.TransportControls controls = getSupportMediaController()
                        .getTransportControls();
                switch (state.getState()) {
                case PlaybackStateCompat.STATE_PLAYING: // fall through
                case PlaybackStateCompat.STATE_BUFFERING:
                    controls.pause();

                    break;
                case PlaybackStateCompat.STATE_PAUSED:
                case PlaybackStateCompat.STATE_STOPPED:
                    controls.play();

                    break;
                default:
                    LogHelper.d(TAG, "onClick with state ", state.getState());
                }
            }
        }
    });

    ;

    // Only update from the intent if we are not recreating from a config change:
    if (savedInstanceState == null) {
        updateFromParams(getIntent());
    }

    mMediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicService.class),
            mConnectionCallback, null);
}

From source file:info.tongrenlu.MediaNotificationManager.java

private Notification createNotification() {

    TrackBean playingTrack = mService.getPlaying();

    long action = mPlaybackState.getActions();
    boolean canPrev = (action & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0;
    boolean canNext = (action & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0;
    boolean isPlaying = mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING;

    Bitmap art = BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art);

    final String artUrl = "http://files.tongrenlu.info/m" + playingTrack.getArticleId() + "/cover_400.jpg";
    //        RequestCreator picasso = Picasso.with(mService.getApplicationContext())
    //                                        .load(artUrl)
    //                                        .placeholder(R.drawable.ic_default_art)
    //                                        .resizeDimen(android.R.dimen.notification_large_icon_width,
    //                                                     android.R.dimen.notification_large_icon_height)
    //                                        .centerCrop();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Notification.Builder builder = new Notification.Builder(mService);
        int playPauseButtonPosition = 0;

        if (canPrev) {
            builder.addAction(R.drawable.ic_skip_previous_white_24dp,
                    mService.getString(R.string.label_previous), mPreviousPendingIntent);
            playPauseButtonPosition = 1;
        }/*from w  w  w .ja  va  2s  . c o m*/

        if (isPlaying) {
            builder.addAction(R.drawable.ic_pause_white_24dp, mService.getString(R.string.label_pause),
                    mTogglePlaybackPendingIntent);
        } else {
            builder.addAction(R.drawable.ic_play_arrow_white_24dp, mService.getString(R.string.label_play),
                    mTogglePlaybackPendingIntent);
        }

        if (canNext) {
            builder.addAction(R.drawable.ic_skip_next_white_24dp, mService.getString(R.string.label_next),
                    mNextPendingIntent);
        }

        builder.setDeleteIntent(mDeletePendingIntent);

        Notification.MediaStyle style = new Notification.MediaStyle();
        style.setShowActionsInCompactView(playPauseButtonPosition);

        builder.setStyle(style).setColor(mNotificationColor).setSmallIcon(R.drawable.ic_notification)
                .setVisibility(Notification.VISIBILITY_PUBLIC).setContentIntent(createContentIntent())
                .setContentTitle(playingTrack.getName()).setContentText(playingTrack.getAlbum())
                .setLargeIcon(art).setOngoing(isPlaying).setAutoCancel(false);

        if (mPlaybackState == null || !mStarted) {
            Log.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
            mService.stopForeground(true);
        } else {
            if (isPlaying && mPlaybackState.getPosition() >= 0) {
                builder.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition());
                builder.setShowWhen(true);
                builder.setUsesChronometer(true);
            } else {
                builder.setWhen(0);
                builder.setShowWhen(false);
                builder.setUsesChronometer(false);
            }
        }
        //
        //            picasso.into(new Target() {
        //                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        //                @Override
        //                public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
        //                    Log.d(TAG, "fetchBitmapFromURLAsync: set bitmap to " + artUrl);
        //                    builder.setLargeIcon(bitmap);
        //                    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        //                }
        //
        //                @Override
        //                public void onBitmapFailed(final Drawable errorDrawable) {
        //
        //                }
        //
        //                @Override
        //                public void onPrepareLoad(final Drawable placeHolderDrawable) {
        //
        //                }
        //            });
        return builder.build();
    } else {
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mService);
        if (canPrev) {
            builder.addAction(R.drawable.ic_skip_previous_white_24dp,
                    mService.getString(R.string.label_previous), mPreviousPendingIntent);
        }

        if (isPlaying) {
            builder.addAction(R.drawable.ic_pause_white_24dp, mService.getString(R.string.label_pause),
                    mTogglePlaybackPendingIntent);
        } else {
            builder.addAction(R.drawable.ic_play_arrow_white_24dp, mService.getString(R.string.label_play),
                    mTogglePlaybackPendingIntent);
        }

        if (canNext) {
            builder.addAction(R.drawable.ic_skip_next_white_24dp, mService.getString(R.string.label_next),
                    mNextPendingIntent);
        }
        builder.setDeleteIntent(mDeletePendingIntent);

        builder.setColor(mNotificationColor).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setSmallIcon(R.drawable.ic_notification).setContentIntent(createContentIntent())
                .setContentTitle(playingTrack.getName()).setContentText(playingTrack.getAlbum())
                .setLargeIcon(art).setOngoing(isPlaying).setAutoCancel(false);

        if (mPlaybackState == null || !mStarted) {
            mService.stopForeground(true);
        } else {
            if (isPlaying && mPlaybackState.getPosition() >= 0) {
                builder.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition());
                builder.setShowWhen(true);
                builder.setUsesChronometer(true);
            } else {
                builder.setWhen(0);
                builder.setShowWhen(false);
                builder.setUsesChronometer(false);
            }

        }
        //
        //            picasso.into(new Target() {
        //                @Override
        //                public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
        //                    Log.d(TAG, "fetchBitmapFromURLAsync: set bitmap to " + artUrl);
        //                    builder.setLargeIcon(bitmap);
        //                    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        //                }
        //
        //                @Override
        //                public void onBitmapFailed(final Drawable errorDrawable) {
        //
        //                }
        //
        //                @Override
        //                public void onPrepareLoad(final Drawable placeHolderDrawable) {
        //
        //                }
        //            });
        return builder.build();
    }
}

From source file:nuclei.media.playback.FallbackPlayback.java

private boolean isStatePlaying() {
    return (isMediaPlayerPlaying() || mState == PlaybackStateCompat.STATE_PLAYING
            || mState == PlaybackStateCompat.STATE_BUFFERING || mState == PlaybackStateCompat.STATE_CONNECTING);
}

From source file:nuclei.media.MediaPlayerController.java

@Override
public int getCurrentPosition() {
    if (isEquals()) {
        PlaybackStateCompat state = mMediaControls.getPlaybackState();
        if (state != null) {
            // KJB: NOTE: Pulled from media compat library
            //            For some reason, it seems, that only API 21 doesn't do something equivalent
            //            of this.  weird.
            //            Just to be safe, since this is important, doing it here.
            //            It's a little redundant... but, I don't see how this would hurt anything
            //            if it were executed twice (so long as getLastPositionUpdateTime is correct)
            //      TODO: revisit this after support library 25.1.1
            try {
                if ((state.getState() == PlaybackStateCompat.STATE_PLAYING
                        || state.getState() == PlaybackStateCompat.STATE_FAST_FORWARDING
                        || state.getState() == PlaybackStateCompat.STATE_REWINDING)) {
                    final long updateTime = state.getLastPositionUpdateTime();
                    final long currentTime = SystemClock.elapsedRealtime();
                    if (updateTime > 0) {
                        final float speed = state.getPlaybackSpeed();
                        final long duration = getDuration();
                        long position = (long) (speed * (currentTime - updateTime)) + state.getPosition();
                        if (duration >= 0 && position > duration) {
                            position = duration;
                        } else if (position < 0) {
                            position = 0;
                        }/*w  w w  .  ja  v  a2  s  .  c  o m*/
                        return (int) position;
                    }
                }
            } catch (Exception err) { // because weird things happen sometimes :(
                LOG.e("Error calculating latest position", err);
            }
            return (int) state.getPosition();
        }
    }
    return -1;
}

From source file:org.runbuddy.tomahawk.mediaplayers.AndroidMediaPlayer.java

private void handlePlayState() {
    if (sMediaPlayer != null && mPreparedQuery != null) {
        try {// w  w  w. j  a  v  a 2 s.  co  m
            if (mPlayState == PlaybackStateCompat.STATE_PAUSED && sMediaPlayer.isPlaying()) {
                sMediaPlayer.pause();
            } else if (mPlayState == PlaybackStateCompat.STATE_PLAYING && !sMediaPlayer.isPlaying()) {
                sMediaPlayer.start();
            }
        } catch (IllegalStateException e) {
            //ignored
        }
    }
}

From source file:com.murati.oszk.audiobook.playback.LocalPlayback.java

@Override
public int getState() {
    if (mExoPlayer == null) {
        return mExoPlayerNullIsStopped ? PlaybackStateCompat.STATE_STOPPED : PlaybackStateCompat.STATE_NONE;
    }/*w  w w.j  av a 2 s . c  o m*/
    switch (mExoPlayer.getPlaybackState()) {
    case ExoPlayer.STATE_IDLE:
        return PlaybackStateCompat.STATE_PAUSED;
    case ExoPlayer.STATE_BUFFERING:
        return PlaybackStateCompat.STATE_BUFFERING;
    case ExoPlayer.STATE_READY:
        return mExoPlayer.getPlayWhenReady() ? PlaybackStateCompat.STATE_PLAYING
                : PlaybackStateCompat.STATE_PAUSED;
    case ExoPlayer.STATE_ENDED:
        return PlaybackStateCompat.STATE_PAUSED;
    default:
        return PlaybackStateCompat.STATE_NONE;
    }
}

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

/**
 * Switch to a different Playback instance, maintaining all playback state, if possible.
 *
 * @param newPlayback switch to this playback
 *//*from ww w.j a v a2s.co m*/
void switchToPlayback(@NonNull Playback newPlayback, boolean resumePlaying) {
    Timber.d("switchToPlayback %s resume %s", newPlayback.getClass().getSimpleName(), resumePlaying);
    // Suspend the current one
    @State
    int oldState = playback.getState();
    int position = playback.getCurrentStreamPosition();
    Track currentMediaId = playback.getCurrentTrack();
    playback.stop(false);
    newPlayback.setCallback(this);
    newPlayback.setCurrentStreamPosition(position < 0 ? 0 : position);
    newPlayback.setCurrentTrack(currentMediaId);
    newPlayback.start();
    // Finally swap the instance
    playback = newPlayback;
    switch (oldState) {
    case PlaybackStateCompat.STATE_BUFFERING:
    case PlaybackStateCompat.STATE_CONNECTING:
    case PlaybackStateCompat.STATE_PAUSED:
        playback.pause();
        break;
    case PlaybackStateCompat.STATE_PLAYING:
        Track currentQueueItem = queueManager.currentTrack();
        if (resumePlaying && currentQueueItem != null) {
            playback.play(currentQueueItem);
        } else if (!resumePlaying) {
            playback.pause();
        } else {
            playback.stop(true);
        }
        break;
    default:
    }
}