Java Code Examples for android.support.v4.media.session.PlaybackStateCompat#STATE_PLAYING

The following examples show how to use android.support.v4.media.session.PlaybackStateCompat#STATE_PLAYING . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TrackNotification.java    From Melophile with Apache License 2.0 6 votes vote down vote up
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
  if (playbackState == null || !isStarted) {
    return;
  }
  if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING
          && playbackState.getPosition() >= 0) {
    builder.setWhen(System.currentTimeMillis() - playbackState.getPosition())
            .setShowWhen(true)
            .setUsesChronometer(true);
  } else {
    builder.setWhen(0)
            .setShowWhen(false)
            .setUsesChronometer(false);
  }
  builder.setOngoing(playbackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
 
Example 2
Source File: TrackNotification.java    From Melophile with Apache License 2.0 6 votes vote down vote up
private Notification createNotification() {
  if (mediaMetadata == null || playbackState == null) return null;
  NotificationCompat.Builder builder = new NotificationCompat.Builder(service);
  builder.setStyle(new NotificationCompat.MediaStyle()
          .setMediaSession(token)
          .setShowActionsInCompactView(1))
          .setColor(Color.WHITE)
          .setPriority(Notification.PRIORITY_MAX)
          .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
          .setUsesChronometer(true)
          .setDeleteIntent(dismissedNotification(service))
          .setSmallIcon(R.drawable.ic_music_note)
          .setContentIntent(contentIntent(service))
          .setContentTitle(mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST))
          .setContentText(mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE))
          .addAction(prev(service));
  if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
    builder.addAction(pause(service));
  } else {
    builder.addAction(play(service));
  }
  builder.addAction(next(service));
  setNotificationPlaybackState(builder);
  loadImage(mediaMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI), builder);
  return builder.build();
}
 
Example 3
Source File: MediaNotificationManager.java    From react-native-audio-streaming-player with MIT License 6 votes vote down vote up
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
    if (mPlaybackState == null || !mStarted) {
        mService.stopForeground(true);
        return;
    }

    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING && mPlaybackState.getPosition() >= 0) {
        builder
            .setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
            .setShowWhen(true)
            .setUsesChronometer(true);
    } else {
        builder
            .setWhen(0)
            .setShowWhen(false)
            .setUsesChronometer(false);
    }

    // Make sure that the notification can be dismissed by the user when we are not playing:
    builder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
 
Example 4
Source File: AudioPlaybackListener.java    From DMAudioStreamer with Apache License 2.0 6 votes vote down vote up
@Override
public void pause() {
    try {
        if (mState == PlaybackStateCompat.STATE_PLAYING) {
            // Pause media player and cancel the 'foreground service' state.
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
                mCurrentPosition = mMediaPlayer.getCurrentPosition();
            }
            // while paused, retain the MediaPlayer but give up audio focus
            relaxResources(false);
        }
        mState = PlaybackStateCompat.STATE_PAUSED;
        if (mCallback != null) {
            mCallback.onPlaybackStatusChanged(mState);
        }
        unregisterAudioNoisyReceiver();
    } catch (IllegalStateException ex) {
        Logger.e(TAG, ex, "Exception pause IllegalStateException");
        ex.printStackTrace();
    }
}
 
Example 5
Source File: AdapterMusic.java    From DMAudioStreamer with Apache License 2.0 6 votes vote down vote up
private Drawable getDrawableByState(Context context, int state) {
    switch (state) {
        case PlaybackStateCompat.STATE_NONE:
            Drawable pauseDrawable = ContextCompat.getDrawable(context, R.drawable.ic_play);
            DrawableCompat.setTintList(pauseDrawable, colorPlay);
            return pauseDrawable;
        case PlaybackStateCompat.STATE_PLAYING:
            AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.equalizer);
            DrawableCompat.setTintList(animation, colorPlay);
            animation.start();
            return animation;
        case PlaybackStateCompat.STATE_PAUSED:
            Drawable playDrawable = ContextCompat.getDrawable(context, R.drawable.equalizer);
            DrawableCompat.setTintList(playDrawable, colorPause);
            return playDrawable;
        default:
            Drawable noneDrawable = ContextCompat.getDrawable(context, R.drawable.ic_play);
            DrawableCompat.setTintList(noneDrawable, colorPlay);
            return noneDrawable;
    }
}
 
Example 6
Source File: MediaSessionPlaybackActivity.java    From media-samples with Apache License 2.0 6 votes vote down vote up
private void initializeMediaSession() {
    mSession = new MediaSessionCompat(this, TAG);
    mSession.setFlags(
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
                    | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mSession.setActive(true);
    MediaControllerCompat.setMediaController(this, mSession.getController());

    MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, mMovieView.getTitle())
            .build();
    mSession.setMetadata(metadata);

    MediaSessionCallback mMediaSessionCallback = new MediaSessionCallback(mMovieView);
    mSession.setCallback(mMediaSessionCallback);

    int state =
            mMovieView.isPlaying()
                    ? PlaybackStateCompat.STATE_PLAYING
                    : PlaybackStateCompat.STATE_PAUSED;
    updatePlaybackState(
            state,
            MEDIA_ACTIONS_ALL,
            mMovieView.getCurrentPosition(),
            mMovieView.getVideoResourceId());
}
 
Example 7
Source File: LocalPlayback.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
@Override
public int getState()
{
    if (exoPlayer == null) {
        return exoPlayerNullIsStopped ? PlaybackStateCompat.STATE_STOPPED : PlaybackStateCompat.STATE_NONE;
    }

    switch (exoPlayer.getPlaybackState()) {
        case STATE_IDLE:
            return PlaybackStateCompat.STATE_PAUSED;
        case STATE_BUFFERING:
            return PlaybackStateCompat.STATE_BUFFERING;
        case STATE_READY:
            return exoPlayer.getPlayWhenReady() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        case STATE_ENDED:
            return PlaybackStateCompat.STATE_PAUSED;
        default:
            return PlaybackStateCompat.STATE_NONE;
    }
}
 
Example 8
Source File: MediaNotificationManager.java    From klingar with Apache License 2.0 6 votes vote down vote up
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
  PlaybackStateCompat playbackState = musicController.getPlaybackState();
  if (playbackState == null || !started) {
    service.stopForeground(true);
    return;
  }
  if (playbackState.getState() == PlaybackStateCompat.STATE_PLAYING
      && playbackState.getPosition() >= 0) {
    builder.setWhen(System.currentTimeMillis() - playbackState.getPosition())
        .setShowWhen(true)
        .setUsesChronometer(true);
  } else {
    builder.setWhen(0)
        .setShowWhen(false)
        .setUsesChronometer(false);
  }
  // Make sure that the notification can be dismissed by the user when we are not playing:
  builder.setOngoing(playbackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
 
Example 9
Source File: MusicPlaybackService.java    From leanback-showcase with Apache License 2.0 5 votes vote down vote up
private void updateMediaSessionPlayState() {
    PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder();
    int playState;
    if (isPlaying()) {
        playState = PlaybackStateCompat.STATE_PLAYING;
    } else {
        playState = PlaybackStateCompat.STATE_PAUSED;
    }
    long currentPosition = getCurrentPosition();
    playbackStateBuilder.setState(playState, currentPosition, (float) 1.0).setActions(
            getPlaybackStateActions()
    );
    mMediaSession.setPlaybackState(playbackStateBuilder.build());
}
 
Example 10
Source File: TrackFragment.java    From Melophile with Apache License 2.0 5 votes vote down vote up
private void updateProgress() {
  if (lastState == null) return;
  long currentPosition = lastState.getPosition();
  if (lastState.getState() == PlaybackStateCompat.STATE_PLAYING) {
    long timeDelta = SystemClock.elapsedRealtime() -
            lastState.getLastPositionUpdateTime();
    currentPosition += (int) timeDelta * lastState.getPlaybackSpeed();
  }
  if (progress != null) {
    progress.setProgress((int) currentPosition);
    startTime.setText(DateUtils.formatElapsedTime(progress.getProgress() / 1000));
  }
}
 
Example 11
Source File: MediaNotificationManager.java    From klingar with Apache License 2.0 5 votes vote down vote up
private void addPlayPauseAction(NotificationCompat.Builder builder) {
  if (state == PlaybackStateCompat.STATE_PLAYING) {
    builder.addAction(new NotificationCompat.Action(R.drawable.ic_notification_pause,
        service.getString(R.string.label_pause), pauseIntent));
  } else {
    builder.addAction(new NotificationCompat.Action(R.drawable.ic_notification_play,
        service.getString(R.string.label_play), playIntent));
  }
}
 
Example 12
Source File: MusicControlModule.java    From react-native-music-control with MIT License 5 votes vote down vote up
@ReactMethod
synchronized public void updatePlayback(ReadableMap info) {
    init();

    long updateTime;
    long elapsedTime;
    long bufferedTime = info.hasKey("bufferedTime") ? (long)(info.getDouble("bufferedTime") * 1000) : state.getBufferedPosition();
    float speed = info.hasKey("speed") ? (float)info.getDouble("speed") : state.getPlaybackSpeed();
    int pbState = info.hasKey("state") ? info.getInt("state") : state.getState();
    int maxVol = info.hasKey("maxVolume") ? info.getInt("maxVolume") : volume.getMaxVolume();
    int vol = info.hasKey("volume") ? info.getInt("volume") : volume.getCurrentVolume();
    ratingType = info.hasKey("rating") ? info.getInt("rating") : ratingType;

    if(info.hasKey("elapsedTime")) {
        elapsedTime = (long)(info.getDouble("elapsedTime") * 1000);
        updateTime = SystemClock.elapsedRealtime();
    } else {
        elapsedTime = state.getPosition();
        updateTime = state.getLastPositionUpdateTime();
    }

    pb.setState(pbState, elapsedTime, speed, updateTime);
    pb.setBufferedPosition(bufferedTime);
    pb.setActions(controls);

    isPlaying = pbState == PlaybackStateCompat.STATE_PLAYING || pbState == PlaybackStateCompat.STATE_BUFFERING;
    if(session.isActive()) notification.show(nb, isPlaying);

    state = pb.build();
    session.setPlaybackState(state);

    session.setRatingType(ratingType);

    if(remoteVolume) {
        session.setPlaybackToRemote(volume.create(null, maxVol, vol));
    } else {
        session.setPlaybackToLocal(AudioManager.STREAM_MUSIC);
    }
}
 
Example 13
Source File: BackgroundAudioService.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void setMediaPlaybackState(int state) {
    PlaybackStateCompat.Builder playbackstateBuilder = new PlaybackStateCompat.Builder();
    if( state == PlaybackStateCompat.STATE_PLAYING ) {
        playbackstateBuilder.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
    } else {
        playbackstateBuilder.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
    }
    playbackstateBuilder.setState(state, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0);
    mMediaSessionCompat.setPlaybackState(playbackstateBuilder.build());
}
 
Example 14
Source File: MusicService.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
/**
 * Update the current media player state, optionally showing an error message.
 *
 * @param error if not null, error message to present to the user.
 */
private void updatePlaybackState(String error) {
    LogUtils.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();
    }
}
 
Example 15
Source File: MediaPlayback.java    From Melophile with Apache License 2.0 5 votes vote down vote up
@Override
public void resumePlayer() {
  if (player != null) {
    if (!player.isPlaying()) {
      player.start();
    }
    playerState = PlaybackStateCompat.STATE_PLAYING;
    if (callback != null) callback.onPlay();
  }
}
 
Example 16
Source File: NotificationHandler.java    From Bop with Apache License 2.0 5 votes vote down vote up
private void addActions(final NotificationCompat.Builder notificationBuilder) {

        notificationBuilder.addAction(R.drawable.ic_previous, "previous", mPreviousIntent);


        // Play or pause button, depending on the current state.
        final String label;
        final int icon;
        final PendingIntent intent;
        if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
            label = "pause";
            icon = R.drawable.ic_pause;
            intent = mPauseIntent;
        } else {
            label = "play";
            icon = R.drawable.ic_play;
            intent = mPlayIntent;
        }
        notificationBuilder.addAction(new NotificationCompat.Action(icon, label, intent));


        notificationBuilder.addAction(R.drawable.ic_skip, "next", mNextIntent);


        notificationBuilder.addAction(R.drawable.ic_cancel, "cancel", mStopIntent);

    }
 
Example 17
Source File: MediaSeekBar.java    From android-MediaBrowserService with Apache License 2.0 5 votes vote down vote up
@Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
    super.onPlaybackStateChanged(state);

    // If there's an ongoing animation, stop it now.
    if (mProgressAnimator != null) {
        mProgressAnimator.cancel();
        mProgressAnimator = null;
    }

    final int progress = state != null
            ? (int) state.getPosition()
            : 0;
    setProgress(progress);

    // If the media is playing then the seekbar should follow it, and the easiest
    // way to do that is to create a ValueAnimator to update it so the bar reaches
    // the end of the media the same time as playback gets there (or close enough).
    if (state != null && state.getState() == PlaybackStateCompat.STATE_PLAYING) {
        final int timeToEnd = (int) ((getMax() - progress) / state.getPlaybackSpeed());

        mProgressAnimator = ValueAnimator.ofInt(progress, getMax())
                .setDuration(timeToEnd);
        mProgressAnimator.setInterpolator(new LinearInterpolator());
        mProgressAnimator.addUpdateListener(this);
        mProgressAnimator.start();
    }
}
 
Example 18
Source File: MediaSessionManager.java    From react-native-jw-media-player with MIT License 5 votes vote down vote up
private void updatePlaybackState(PlayerState playerState) {
	PlaybackStateCompat.Builder newPlaybackState = getPlaybackStateBuilder();
	long capabilities = getCapabilities(playerState);
	//noinspection WrongConstant
	newPlaybackState.setActions(capabilities);

	int playbackStateCompat = PlaybackStateCompat.STATE_NONE;
	switch (playerState) {
		case PLAYING:
			playbackStateCompat = PlaybackStateCompat.STATE_PLAYING;
			break;
		case PAUSED:
			playbackStateCompat = PlaybackStateCompat.STATE_PAUSED;
			break;
		case BUFFERING:
			playbackStateCompat = PlaybackStateCompat.STATE_BUFFERING;
			break;
		case IDLE:
			if (mReceivedError) {
				playbackStateCompat = PlaybackStateCompat.STATE_ERROR;
			} else {
				playbackStateCompat = PlaybackStateCompat.STATE_STOPPED;
			}
			break;
	}

	if (mPlayer != null) {
		newPlaybackState.setState(playbackStateCompat, (long)mPlayer.getPosition(), mPlayer.getPlaybackRate()); // PLAYBACK_RATE
		mMediaSessionCompat.setPlaybackState(newPlaybackState.build());
		mNotificationWrapper
				.createNotification(mPlayer.getContext(), mMediaSessionCompat, capabilities);
	}
}
 
Example 19
Source File: LocalPlayback.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
/**
 * Called when MediaPlayer has completed a seek
 *
 * @see OnSeekCompleteListener
 */
@Override
public void onSeekComplete(MediaPlayer mp) {
    LogUtils.d(TAG, "onSeekComplete from MediaPlayer:", mp.getCurrentPosition());
    mCurrentPosition = mp.getCurrentPosition();
    if (mState == PlaybackStateCompat.STATE_BUFFERING) {
        mMediaPlayer.start();
        mState = PlaybackStateCompat.STATE_PLAYING;
    }
    if (mCallback != null) {
        mCallback.onPlaybackStatusChanged(mState);
    }
}
 
Example 20
Source File: NotificationBuilder.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
private boolean isPlaying()
{
    return (playbackState.getActions() & PlaybackStateCompat.STATE_PLAYING) != 0;
}