android.media.session.PlaybackState Java Examples

The following examples show how to use android.media.session.PlaybackState. 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: MusicService.java    From android-music-player with Apache License 2.0 7 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Start a new MediaSession
    mSession = new MediaSession(this, "MusicService");
    mSession.setCallback(mCallback);
    mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
            MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    setSessionToken(mSession.getSessionToken());

    final MediaNotificationManager mediaNotificationManager = new MediaNotificationManager(this);

    mPlayback = new PlaybackManager(this, new PlaybackManager.Callback() {
        @Override
        public void onPlaybackStatusChanged(PlaybackState state) {
            mSession.setPlaybackState(state);
            mediaNotificationManager.update(mPlayback.getCurrentMedia(), state, getSessionToken());
        }
    });
}
 
Example #2
Source File: MusicPlayerActivity.java    From android-music-player with Apache License 2.0 7 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MediaBrowser.MediaItem item = getItem(position);
    int itemState = MediaItemViewHolder.STATE_NONE;
    if (item.isPlayable()) {
        String itemMediaId = item.getDescription().getMediaId();
        int playbackState = PlaybackState.STATE_NONE;
        if (mCurrentState != null) {
            playbackState = mCurrentState.getState();
        }
        if (mCurrentMetadata != null &&
                itemMediaId.equals(mCurrentMetadata.getDescription().getMediaId())) {
            if (playbackState == PlaybackState.STATE_PLAYING ||
                playbackState == PlaybackState.STATE_BUFFERING) {
                itemState = MediaItemViewHolder.STATE_PLAYING;
            } else if (playbackState != PlaybackState.STATE_ERROR) {
                itemState = MediaItemViewHolder.STATE_PAUSED;
            }
        }
    }
    return MediaItemViewHolder.setupView((Activity) getContext(), convertView, parent,
        item.getDescription(), itemState);
}
 
Example #3
Source File: ClementineMediaSessionV21.java    From Android-Remote with GNU General Public License v3.0 6 votes vote down vote up
private void updatePlayState() {
    PlaybackState.Builder builder = new PlaybackState.Builder();
    switch (App.Clementine.getState()) {
        case PLAY:
            builder.setState(PlaybackState.STATE_PLAYING, App.Clementine.getSongPosition(),
                    1.0f);
            break;
        case PAUSE:
            builder.setState(PlaybackState.STATE_PAUSED, App.Clementine.getSongPosition(),
                    1.0f);
            break;
        case STOP:
            builder.setState(PlaybackState.STATE_STOPPED, 0, 1.0f);
            break;
        default:
            break;
    }

    mMediaSession.setPlaybackState(builder.build());
}
 
Example #4
Source File: MediaController2Lollipop.java    From AcDisplay with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(@NonNull MediaController2 mc) {
    final MediaController2Lollipop mcl = (MediaController2Lollipop) mc;
    final MediaController source = mcl.mMediaController;

    if (source != null && mToken.equals(source.getSessionToken())) {
        long now = SystemClock.elapsedRealtime();

        final MediaMetadata metadata = source.getMetadata();
        final PlaybackState playbackState = source.getPlaybackState();

        long delta = SystemClock.elapsedRealtime() - now;
        Log.i(TAG, "Got the new metadata & playback state in " + delta + " millis. "
                + "The media controller is " + source.getPackageName());

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mcl.updateMetadata(metadata);
                mcl.updatePlaybackState(playbackState);
            }
        });
    }
}
 
Example #5
Source File: MusicPlayerActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    final int state = mCurrentState == null ?
            PlaybackState.STATE_NONE : mCurrentState.getState();
    if (state == PlaybackState.STATE_PAUSED ||
            state == PlaybackState.STATE_STOPPED ||
            state == PlaybackState.STATE_NONE) {

        if (mCurrentMetadata == null) {
            mCurrentMetadata = MusicLibrary.getMetadata(MusicPlayerActivity.this,
                    MusicLibrary.getMediaItems().get(0).getMediaId());
            updateMetadata(mCurrentMetadata);
        }
        getMediaController().getTransportControls().playFromMediaId(
                mCurrentMetadata.getDescription().getMediaId(), null);

    } else {
        getMediaController().getTransportControls().pause();
    }
}
 
Example #6
Source File: PlaybackControlBaseActivity.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the MediaSession is active and in a "playback-able" state
 * (not NONE and not STOPPED).
 *
 * @return true if the MediaSession's state requires playback controls to be visible.
 */
protected boolean shouldShowControls() {
    MediaControllerCompat mediaController = mMediaController;
    if (mediaController == null ||
            mediaController.getMetadata() == null ||
            mediaController.getPlaybackState() == null) {
        return false;
    }
    switch (mediaController.getPlaybackState().getState()) {
        case PlaybackState.STATE_ERROR:
        case PlaybackState.STATE_NONE:
        case PlaybackState.STATE_STOPPED:
            return false;
        default:
            return true;
    }
}
 
Example #7
Source File: AutoMediaBrowserService.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void toggleMediaPlaybackState( boolean playing ) {
    PlaybackState playbackState;
    if( playing ) {
        playbackState = new PlaybackState.Builder()
                .setActions( PlaybackState.ACTION_PLAY_PAUSE | PlaybackState.ACTION_SKIP_TO_NEXT | PlaybackState.ACTION_SKIP_TO_PREVIOUS )
                .setState( PlaybackState.STATE_PLAYING, 0, 1 )
                .build();
    } else {
        playbackState = new PlaybackState.Builder()
                .setActions( PlaybackState.ACTION_PLAY_PAUSE )
                .setState(PlaybackState.STATE_PAUSED, 0, 1)
                .build();
    }

    mMediaSession.setPlaybackState( playbackState );
}
 
Example #8
Source File: VideoPlayerActivity.java    From iview-android-tv with MIT License 6 votes vote down vote up
private void updatePlaybackState(int playbackState) {
    PlaybackState.Builder state = new PlaybackState.Builder();
    long position = player.getCurrentPosition();
    if (ExoPlayer.STATE_PREPARING == playbackState) {
        state.setState(PlaybackState.STATE_CONNECTING, position, 1.0f);
    } else if (ExoPlayer.STATE_BUFFERING == playbackState) {
        state.setState(PlaybackState.STATE_BUFFERING, position, 1.0f);
    } else {
        if (player.getPlayerControl().isPlaying()) {
            state.setState(PlaybackState.STATE_PLAYING, position, 1.0f);
        } else {
            state.setState(PlaybackState.STATE_PAUSED, position, 1.0f);
        }
    }
    mediaSession.setPlaybackState(state.build());
}
 
Example #9
Source File: PlayerState.java    From scroball with MIT License 6 votes vote down vote up
public void setPlaybackState(PlaybackState playbackState) {
  if (playbackItem == null) {
    return;
  }

  playbackItem.updateAmountPlayed();

  int state = playbackState.getState();
  boolean isPlaying = state == PlaybackState.STATE_PLAYING;

  if (isPlaying) {
    Log.d(TAG, "Track playing");
    postEvent(playbackItem.getTrack());
    playbackItem.startPlaying();
    notificationManager.updateNowPlaying(playbackItem.getTrack());
    scheduleSubmission();
  } else {
    Log.d(TAG, String.format("Track paused (state %d)", state));
    postEvent(Track.empty());
    playbackItem.stopPlaying();
    notificationManager.removeNowPlaying();
    scrobbler.submit(playbackItem);
  }
}
 
Example #10
Source File: MediaPlayback.java    From PodEmu with GNU General Public License v3.0 6 votes vote down vote up
public void action_play_pause()
{
    PodEmuLog.debug("PEMP: action PLAY_PAUSE requested");
    MediaController mediaController=getActiveMediaController();
    if( mediaController!=null && mediaController.getPlaybackState()!=null && mediaController.getTransportControls()!=null)// && (mediaController.getPlaybackState().getActions() & PlaybackState.ACTION_PLAY_PAUSE) == PlaybackState.ACTION_PLAY_PAUSE)
    {
        PodEmuLog.debug("PEMP: executing action through MediaController (ACTION_PLAY_PAUSE)");
        if(mediaController.getPlaybackState().getState() == PlaybackState.STATE_PLAYING)
            mediaController.getTransportControls().pause();
        else
            mediaController.getTransportControls().play();
    }
    else
    {
        PodEmuLog.debug("PEMP: executing action through KeyEvent");
        execute_action(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
    }
}
 
Example #11
Source File: MusicPlayerActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    // ------------ CHANGE 3 - REMOVE FOLLOWING LINES FOR PLAYBACK ON A SERVICE
    mPlaybackManager = new PlaybackManager(this, new PlaybackManager.Callback() {
        @Override
        public void onPlaybackStatusChanged(PlaybackState state) {
            mBrowserAdapter.notifyDataSetChanged();
            updatePlaybackState(state);
        }
    });
    onMediaLoaded(MusicLibrary.getMediaItems());

    /* ------------ CHANGE 3 - UNCOMMENT FOLLOWING LINES FOR PLAYBACK ON A SERVICE
    mMediaBrowser = new MediaBrowser(this,
           new ComponentName(this, MusicService.class), mConnectionCallback, null);
    mMediaBrowser.connect();
    // ------------ CHANGE 3 - END OF PLAYBACK ON A SERVICE SNIPPET */
}
 
Example #12
Source File: MusicPlayerActivity.java    From android-music-player with Apache License 2.0 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MediaBrowser.MediaItem item = getItem(position);
    int itemState = MediaItemViewHolder.STATE_NONE;
    if (item.isPlayable()) {
        String itemMediaId = item.getDescription().getMediaId();
        int playbackState = PlaybackState.STATE_NONE;
        if (mCurrentState != null) {
            playbackState = mCurrentState.getState();
        }
        if (mCurrentMetadata != null &&
                itemMediaId.equals(mCurrentMetadata.getDescription().getMediaId())) {
            if (playbackState == PlaybackState.STATE_PLAYING ||
                playbackState == PlaybackState.STATE_BUFFERING) {
                itemState = MediaItemViewHolder.STATE_PLAYING;
            } else if (playbackState != PlaybackState.STATE_ERROR) {
                itemState = MediaItemViewHolder.STATE_PAUSED;
            }
        }
    }
    return MediaItemViewHolder.setupView((Activity) getContext(), convertView, parent,
        item.getDescription(), itemState);
}
 
Example #13
Source File: MusicService.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // Start a new MediaSession
    mSession = new MediaSession(this, "MusicService");
    mSession.setCallback(mCallback);
    mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
            MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
    setSessionToken(mSession.getSessionToken());

    final MediaNotificationManager mediaNotificationManager = new MediaNotificationManager(this);

    mPlayback = new PlaybackManager(this, new PlaybackManager.Callback() {
        @Override
        public void onPlaybackStatusChanged(PlaybackState state) {
            mSession.setPlaybackState(state);
            mediaNotificationManager.update(mPlayback.getCurrentMedia(), state, getSessionToken());
        }
    });
}
 
Example #14
Source File: MediaControllerCallback.java    From QuickLyric with GNU General Public License v3.0 6 votes vote down vote up
public static long getActiveControllerPosition(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sController.get() != null) {
        PlaybackState state = sController.get().getPlaybackState();
        if (state != null)
            return state.getPosition();
    } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        long kitkatPosition = NotificationListenerService.getRemotePlayerPosition();
        if (kitkatPosition >= 0)
            return kitkatPosition;
    }
    SharedPreferences preferences = context.getSharedPreferences("current_music", Context.MODE_PRIVATE);
    long startTime = preferences.getLong("startTime", System.currentTimeMillis());
    long distance = System.currentTimeMillis() - startTime;
    long position = preferences.getLong("position", -1L);
    if (preferences.getBoolean("playing", true) && position >= 0L)
        position += distance;
    return position;
}
 
Example #15
Source File: MusicPlayerActivity.java    From android-music-player with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
    super.onStart();

    // ------------ CHANGE 3 - REMOVE FOLLOWING LINES FOR PLAYBACK ON A SERVICE
    mPlaybackManager = new PlaybackManager(this, new PlaybackManager.Callback() {
        @Override
        public void onPlaybackStatusChanged(PlaybackState state) {
            mBrowserAdapter.notifyDataSetChanged();
            updatePlaybackState(state);
        }
    });
    onMediaLoaded(MusicLibrary.getMediaItems());

    /* ------------ CHANGE 3 - UNCOMMENT FOLLOWING LINES FOR PLAYBACK ON A SERVICE
    mMediaBrowser = new MediaBrowser(this,
           new ComponentName(this, MusicService.class), mConnectionCallback, null);
    mMediaBrowser.connect();
    // ------------ CHANGE 3 - END OF PLAYBACK ON A SERVICE SNIPPET */
}
 
Example #16
Source File: MusicPlayerActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MediaBrowser.MediaItem item = getItem(position);
    int itemState = MediaItemViewHolder.STATE_NONE;
    if (item.isPlayable()) {
        String itemMediaId = item.getDescription().getMediaId();
        int playbackState = PlaybackState.STATE_NONE;
        if (mCurrentState != null) {
            playbackState = mCurrentState.getState();
        }
        if (mCurrentMetadata != null &&
                itemMediaId.equals(mCurrentMetadata.getDescription().getMediaId())) {
            if (playbackState == PlaybackState.STATE_PLAYING ||
                playbackState == PlaybackState.STATE_BUFFERING) {
                itemState = MediaItemViewHolder.STATE_PLAYING;
            } else if (playbackState != PlaybackState.STATE_ERROR) {
                itemState = MediaItemViewHolder.STATE_PAUSED;
            }
        }
    }
    return MediaItemViewHolder.setupView((Activity) getContext(), convertView, parent,
        item.getDescription(), itemState);
}
 
Example #17
Source File: MediaSessionRecord.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void setPlaybackState(PlaybackState state) {
    int oldState = mPlaybackState == null
            ? PlaybackState.STATE_NONE : mPlaybackState.getState();
    int newState = state == null
            ? PlaybackState.STATE_NONE : state.getState();
    synchronized (mLock) {
        mPlaybackState = state;
    }
    final long token = Binder.clearCallingIdentity();
    try {
        mService.onSessionPlaystateChanged(MediaSessionRecord.this, oldState, newState);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
    mHandler.post(MessageHandler.MSG_UPDATE_PLAYBACK_STATE);
}
 
Example #18
Source File: PlaybackOverlayFragment.java    From BuildingForAndroidTV with MIT License 6 votes vote down vote up
@Override
public void onPlaybackStateChanged(PlaybackState state) {
    Log.d(TAG, "playback state changed: " + state.getState());
    if (state.getState() == PlaybackState.STATE_PLAYING && mCurrentPlaybackState != PlaybackState.STATE_PLAYING) {
        mCurrentPlaybackState = PlaybackState.STATE_PLAYING;
        startProgressAutomation();
        setFadingEnabled(true);
        mPlayPauseAction.setIndex(PlayPauseAction.PAUSE);
        mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PAUSE));
        notifyChanged(mPlayPauseAction);
    } else if (state.getState() == PlaybackState.STATE_PAUSED && mCurrentPlaybackState != PlaybackState.STATE_PAUSED) {
        mCurrentPlaybackState = PlaybackState.STATE_PAUSED;
        stopProgressAutomation();
        setFadingEnabled(false);
        mPlayPauseAction.setIndex(PlayPauseAction.PLAY);
        mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PLAY));
        notifyChanged(mPlayPauseAction);
    }

    int currentTime = (int)state.getPosition();
    mPlaybackControlsRow.setCurrentTime(currentTime);
    mPlaybackControlsRow.setBufferedProgress(currentTime + SIMULATED_BUFFERED_TIME);
}
 
Example #19
Source File: MediaSessionPlaybackActivityTest.java    From android-PictureInPicture with Apache License 2.0 5 votes vote down vote up
private void assertMediaStateIs(@PlaybackStateCompat.State int expectedState) {
    PlaybackState state = rule.getActivity().getMediaController().getPlaybackState();
    assertNotNull(state);
    assertThat(
            "MediaSession is not in the correct state",
            state.getState(),
            is(equalTo(expectedState)));
}
 
Example #20
Source File: PlaybackActivity.java    From BuildingForAndroidTV with MIT License 5 votes vote down vote up
private void updatePlaybackState() {
    PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
            .setActions(getAvailableActions());
    int state = PlaybackState.STATE_PLAYING;
    if (mPlaybackState == LeanbackPlaybackState.PAUSED || mPlaybackState == LeanbackPlaybackState.IDLE) {
        state = PlaybackState.STATE_PAUSED;
    }
    stateBuilder.setState(state, mVideoView.getCurrentPosition(), 1.0f);
    mSession.setPlaybackState(stateBuilder.build());
}
 
Example #21
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
private long getAvailableActions() {
    long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID |
            PlaybackState.ACTION_PLAY_FROM_SEARCH |
            PlaybackState.ACTION_SKIP_TO_NEXT  | PlaybackState.ACTION_SKIP_TO_PREVIOUS;
    if (isPlaying()) {
        actions |= PlaybackState.ACTION_PAUSE;
    }
    return actions;
}
 
Example #22
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
public void stop() {
    mState = PlaybackState.STATE_STOPPED;
    updatePlaybackState();
    // Give up Audio focus
    mAudioManager.abandonAudioFocus(this);
    // Relax all resources
    releaseMediaPlayer();
}
 
Example #23
Source File: PlaybackTracker.java    From scroball with MIT License 5 votes vote down vote up
public void handleSessionTermination(String player) {
  PlayerState playerState = getOrCreatePlayerState(player);
  PlaybackState playbackState =
      new PlaybackState.Builder()
          .setState(PlaybackState.STATE_PAUSED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 1)
          .build();
  playerState.setPlaybackState(playbackState);
}
 
Example #24
Source File: MusicPlayerActivity.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
private void updatePlaybackState(PlaybackState state) {
    mCurrentState = state;
    if (state == null || state.getState() == PlaybackState.STATE_PAUSED ||
            state.getState() == PlaybackState.STATE_STOPPED) {
        mPlayPause.setImageDrawable(getDrawable(R.drawable.ic_play_arrow_black_36dp));
    } else {
        mPlayPause.setImageDrawable(getDrawable(R.drawable.ic_pause_black_36dp));
    }
    mPlaybackControls.setVisibility(state == null ? View.GONE : View.VISIBLE);
}
 
Example #25
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
public void pause() {
    if (isPlaying()) {
        mMediaPlayer.pause();
        mAudioManager.abandonAudioFocus(this);
    }
    mState = PlaybackState.STATE_PAUSED;
    updatePlaybackState();
}
 
Example #26
Source File: PlaybackManager.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
private void updatePlaybackState() {
    if (mCallback == null) {
        return;
    }
    PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
            .setActions(getAvailableActions());

    stateBuilder.setState(mState, getCurrentStreamPosition(), 1.0f, SystemClock.elapsedRealtime());
    mCallback.onPlaybackStatusChanged(stateBuilder.build());
}
 
Example #27
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
public void pause() {
    if (isPlaying()) {
        mMediaPlayer.pause();
        mAudioManager.abandonAudioFocus(this);
    }
    mState = PlaybackState.STATE_PAUSED;
    updatePlaybackState();
}
 
Example #28
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
public void stop() {
    mState = PlaybackState.STATE_STOPPED;
    updatePlaybackState();
    // Give up Audio focus
    mAudioManager.abandonAudioFocus(this);
    // Relax all resources
    releaseMediaPlayer();
}
 
Example #29
Source File: PlaybackManager.java    From android-music-player with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example #30
Source File: PlaybackOverlayFragment.java    From BuildingForAndroidTV with MIT License 5 votes vote down vote up
private void prev(boolean autoPlay) {
    if (--mCurrentItem < 0) {
        mCurrentItem = mItems.size() - 1;
    }
    Bundle bundle = new Bundle();
    bundle.putBoolean(PlaybackActivity.AUTO_PLAY, autoPlay);
    if (autoPlay) {
        mCurrentPlaybackState = PlaybackState.STATE_PAUSED;
    }
    mMediaController.getTransportControls().playFromMediaId(mItems.get(mCurrentItem).getId(), bundle);
    mFfwRwdSpeed = INITIAL_SPEED;
}