List of usage examples for android.support.v4.media.session PlaybackStateCompat STATE_PLAYING
int STATE_PLAYING
To view the source code for android.support.v4.media.session PlaybackStateCompat STATE_PLAYING.
Click Source Link
From source file:nuclei.media.playback.ExoPlayerPlayback.java
/** * Reconfigures MediaPlayer according to audio focus settings and * starts/restarts it. This method starts/restarts the MediaPlayer * respecting the current audio focus state. So if we have focus, it will * play normally; if we don't have focus, it will either leave the * MediaPlayer paused or set it to a low volume, depending on what is * allowed by the current focus settings. This method assumes mPlayer != * null, so if you are calling it, you have to do so from a context where * you are sure this is the case./*from w w w . j av a 2s . com*/ */ private void configMediaPlayerState(boolean updateMetaData, boolean forcePlay) { if (LOG.isLoggable(Log.DEBUG)) LOG.d("configMediaPlayerState. mAudioFocus=" + mAudioFocus); if (mAudioFocus == AUDIO_NO_FOCUS_NO_DUCK) { // If we don't have audio focus and can't duck, we have to pause, if (isPlaying()) { pause(); } } else { // we have audio focus: if (mAudioFocus == AUDIO_NO_FOCUS_CAN_DUCK) { if (mMediaPlayer != null) { mMediaPlayer.setVolume(VOLUME_DUCK); // we'll be relatively quiet } } else { if (mMediaPlayer != null) { mMediaPlayer.setVolume(VOLUME_NORMAL); // we can be loud again } // else do something for remote client. } // If we were playing when we lost focus, we need to resume playing. if (mPlayOnFocusGain && mPlayWhenReady) { if (!isMediaPlayerPlaying()) { if (LOG.isLoggable(Log.INFO)) LOG.d("configMediaPlayerState startMediaPlayer. seeking to " + mCurrentPosition); if (mState == PlaybackStateCompat.STATE_PAUSED || mState == PlaybackStateCompat.STATE_STOPPED) { if (forcePlay || mCurrentPosition != mMediaPlayer.getCurrentPosition()) { if (!mWakeLock.isHeld()) mWakeLock.acquire(); if (!mWifiLock.isHeld()) mWifiLock.acquire(); mState = PlaybackStateCompat.STATE_BUFFERING; mMediaPlayer.seekTo(mCurrentPosition); mMediaPlayer.setPlayWhenReady(true); } else mState = PlaybackStateCompat.STATE_PLAYING; } else { mMediaPlayer.seekTo(mCurrentPosition); mState = PlaybackStateCompat.STATE_BUFFERING; } } mPlayOnFocusGain = false; } } if (mCallback != null) { if (updateMetaData) mCallback.onMetadataChanged(mMediaMetadata); mCallback.onPlaybackStatusChanged(mState); } }
From source file:org.runbuddy.tomahawk.services.PlaybackService.java
public void play(boolean onAudioFocusGain) { Log.d(TAG, "play"); if (onAudioFocusGain && !mPlayOnFocusGain) { return;//from ww w .j a va 2 s. c o m } if (mPlaybackManager.getCurrentQuery() != null) { if (mAudioBecomingNoisyReceiver == null) { mAudioBecomingNoisyReceiver = new AudioBecomingNoisyReceiver(); registerReceiver(mAudioBecomingNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)); } mSuicideHandler.stop(); mSuicideHandler.reset(); mPluginServiceKillHandler.stop(); mPluginServiceKillHandler.reset(); mScrobbleHandler.start(); mPlayState = PlaybackStateCompat.STATE_PLAYING; handlePlayState(); tryToGetAudioFocus(); updateMediaPlayState(); mNotification.startNotification(); } }
From source file:org.chromium.chrome.browser.media.ui.NotificationMediaPlaybackControls.java
private void updateNotification() { if (mService == null) return;//w ww.j a va 2s . co m if (mMediaNotificationInfo == null) { // Notification was hidden before we could update it. assert mNotificationBuilder == null; return; } // Android doesn't badge the icons for RemoteViews automatically when // running the app under the Work profile. if (mNotificationIcon == null) { Drawable notificationIconDrawable = ApiCompatibilityUtils.getUserBadgedIcon(mContext, R.drawable.audio_playing); mNotificationIcon = drawableToBitmap(notificationIconDrawable); } if (mNotificationBuilder == null) { mNotificationBuilder = new NotificationCompat.Builder(mContext).setSmallIcon(R.drawable.audio_playing) .setAutoCancel(false).setLocalOnly(true) .setDeleteIntent(mService.getPendingIntent(ListenerService.ACTION_STOP)); } mNotificationBuilder.setOngoing(!mMediaNotificationInfo.isPaused); mNotificationBuilder.setContentIntent(createContentIntent()); RemoteViews contentView = createContentView(); contentView.setTextViewText(R.id.title, mMediaNotificationInfo.title); contentView.setTextViewText(R.id.status, getStatus()); if (mNotificationIcon != null) { contentView.setImageViewBitmap(R.id.icon, mNotificationIcon); } else { contentView.setImageViewResource(R.id.icon, R.drawable.audio_playing); } if (mMediaNotificationInfo.isPaused) { contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_play); contentView.setContentDescription(R.id.playpause, mPlayDescription); contentView.setOnClickPendingIntent(R.id.playpause, mService.getPendingIntent(ListenerService.ACTION_PLAY)); } else { contentView.setImageViewResource(R.id.playpause, R.drawable.ic_vidcontrol_pause); contentView.setContentDescription(R.id.playpause, mPauseDescription); contentView.setOnClickPendingIntent(R.id.playpause, mService.getPendingIntent(ListenerService.ACTION_PAUSE)); } mNotificationBuilder.setContent(contentView); mNotificationBuilder.setVisibility(mMediaNotificationInfo.isPrivate ? NotificationCompat.VISIBILITY_PRIVATE : NotificationCompat.VISIBILITY_PUBLIC); if (mMediaSession == null) { mMediaSession = new MediaSessionCompat(mContext, mContext.getString(R.string.app_name), new ComponentName(mContext.getPackageName(), MediaButtonReceiver.class.getName()), null); mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); mMediaSession.setCallback(mMediaSessionCallback); mMediaSession.setActive(true); } mMediaSession.setMetadata(createMetadata()); PlaybackStateCompat.Builder playbackStateBuilder = new PlaybackStateCompat.Builder() .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE); if (mMediaNotificationInfo.isPaused) { playbackStateBuilder.setState(PlaybackStateCompat.STATE_PAUSED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); } else { playbackStateBuilder.setState(PlaybackStateCompat.STATE_PLAYING, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f); } mMediaSession.setPlaybackState(playbackStateBuilder.build()); Notification notification = mNotificationBuilder.build(); // We keep the service as a foreground service while the media is playing. When it is not, // the service isn't stopped but is no longer in foreground, thus at a lower priority. // While the service is in foreground, the associated notification can't be swipped away. // Moving it back to background allows the user to remove the notification. if (mMediaNotificationInfo.isPaused) { mService.stopForeground(false /* removeNotification */); NotificationManagerCompat manager = NotificationManagerCompat.from(mContext); manager.notify(R.id.media_playback_notification, notification); } else { mService.startForeground(R.id.media_playback_notification, notification); } }
From source file:org.tomahawk.tomahawk_android.utils.MediaNotification.java
private void updateNotificationPlaybackState() { Log.d(TAG, "updateNotificationPlaybackState. mPlaybackState=" + mPlaybackState); if (mPlaybackState == null || !mStarted) { Log.d(TAG, "updateNotificationPlaybackState. cancelling notification!"); mService.stopForeground(true);/* w w w. j av a2 s .co m*/ return; } if (mNotificationBuilder == null) { Log.d(TAG, "updateNotificationPlaybackState. there is no notificationBuilder. " + "Ignoring request to update state!"); return; } if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && mPlaybackState.getPosition() >= 0 && mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) { Log.d(TAG, "updateNotificationPlaybackState. updating playback position to " + (System.currentTimeMillis() - mPlaybackState.getPosition()) / 1000 + " seconds"); mNotificationBuilder.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition()) .setShowWhen(true).setUsesChronometer(true); } else { Log.d(TAG, "updateNotificationPlaybackState. hiding playback position"); mNotificationBuilder.setWhen(0).setShowWhen(false).setUsesChronometer(false); } updatePlayPauseAction(); // Make sure that the notification can be dismissed by the user when we are not playing: mNotificationBuilder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING); if (mPlaybackState.getState() != PlaybackStateCompat.STATE_PLAYING) { mService.stopForeground(false); } }
From source file:com.scooter1556.sms.android.fragment.tv.TvVideoPlayerFragment.java
private void startSeeking() { Log.d(TAG, "startSeeking()"); if (playbackState != PlaybackStateCompat.STATE_PLAYING && playbackState != PlaybackStateCompat.STATE_PAUSED) { return;//ww w . j av a 2 s . co m } if (playbackState == PlaybackStateCompat.STATE_PLAYING) { pause(); } seekInProgress = true; setFadingEnabled(false); stopProgressAutomation(); if (seekRunnable == null) { seekRunnable = new Runnable() { @Override public void run() { int currentTime = playbackControlsRow.getCurrentTime() + seekSpeed; if (currentTime < 0) { currentPosition = 0; playbackControlsRow.setCurrentTime(0); } else if (currentTime > playbackControlsRow.getTotalTime()) { getActivity().finish(); } else { currentPosition = currentTime; playbackControlsRow.setCurrentTime(currentTime); seekHandler.postDelayed(this, DEFAULT_SEEK_DELAY); } } }; seekHandler.postDelayed(seekRunnable, DEFAULT_SEEK_DELAY); } }
From source file:com.andryr.musicplayer.PlaybackService.java
private void updateMediaSession(String what) { if (!mMediaSession.isActive()) { mMediaSession.setActive(true);//ww w. ja v a2s.co m } if (what.equals(PLAYSTATE_CHANGED)) { int playState = isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED; mMediaSession.setPlaybackState(new PlaybackStateCompat.Builder() .setState(playState, getPlayerPosition(), 1.0F) .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) .build()); } if (what.equals(META_CHANGED)) { int largeArtSize = (int) getResources().getDimension(R.dimen.art_size); Bitmap artwork = ArtworkCache.getInstance().getCachedBitmap(getAlbumId(), largeArtSize, largeArtSize); MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName()) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName()) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getSongTitle()) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, getTrackDuration()) .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, artwork); mMediaSession.setMetadata(builder.build()); } }
From source file:com.example.android.leanback.MediaSessionService.java
/** * Prepare the first item in the list. And setup the listener for media player. *//*from w ww .j av a2 s . co 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:nuclei.media.playback.ExoPlayerPlayback.java
/** * Called by AudioManager on audio focus changes. * Implementation of {@link AudioManager.OnAudioFocusChangeListener} *///ww w . j av a2s .co m @Override public void onAudioFocusChange(int focusChange) { if (LOG.isLoggable(Log.INFO)) LOG.d("onAudioFocusChange. focusChange=" + focusChange); if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { // We have gained focus: mAudioFocus = AUDIO_FOCUSED; } 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. boolean canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK; mAudioFocus = canDuck ? AUDIO_NO_FOCUS_CAN_DUCK : AUDIO_NO_FOCUS_NO_DUCK; // If we are playing, we need to reset media player by calling configMediaPlayerState // with mAudioFocus properly set. if (mState == PlaybackStateCompat.STATE_PLAYING && !canDuck) { // If we don't have audio focus and can't duck, we save the information that // we were playing, so that we can resume playback once we get the focus back. mPlayOnFocusGain = true; } } else { LOG.e("onAudioFocusChange: Ignoring unsupported focusChange: " + focusChange); } configMediaPlayerState(false, false); }
From source file:com.scooter1556.sms.android.fragment.tv.TvAudioPlayerFragment.java
private void updatePlaybackState(PlaybackStateCompat state) { if (state == null || playbackControlsRow == null) { return;// w w w. j av a2 s .c om } lastPlaybackState = state; switch (state.getState()) { case PlaybackStateCompat.STATE_PLAYING: scheduleSeekbarUpdate(); playPauseAction.setIndex(PlayPauseAction.PAUSE); break; case PlaybackStateCompat.STATE_PAUSED: stopSeekbarUpdate(); playPauseAction.setIndex(PlayPauseAction.PLAY); break; case PlaybackStateCompat.STATE_NONE: stopSeekbarUpdate(); playPauseAction.setIndex(PlayPauseAction.PLAY); resetPlaybackRow(); updatePlayListRow(); break; case PlaybackStateCompat.STATE_STOPPED: stopSeekbarUpdate(); playPauseAction.setIndex(PlayPauseAction.PLAY); playbackControlsRow.setCurrentTime(0); break; case PlaybackStateCompat.STATE_BUFFERING: stopSeekbarUpdate(); break; default: Log.d(TAG, "Unhandled state: " + state.getState()); } // Custom Actions for (PlaybackStateCompat.CustomAction action : state.getCustomActions()) { switch (action.getAction()) { case MediaService.STATE_SHUFFLE_ON: shuffleAction.setIcon( ContextCompat.getDrawable(getActivity(), R.drawable.ic_shuffle_enabled_white_48dp)); // Update interface if necessary if (shuffleMode == null || !shuffleMode.equals(MediaService.STATE_SHUFFLE_ON)) { shuffleMode = MediaService.STATE_SHUFFLE_ON; updatePlayListRow(); } break; case MediaService.STATE_SHUFFLE_OFF: shuffleAction.setIcon(ContextCompat.getDrawable(getActivity(), R.drawable.ic_shuffle_white_48dp)); // Update interface if necessary if (shuffleMode == null || !shuffleMode.equals(MediaService.STATE_SHUFFLE_OFF)) { shuffleMode = MediaService.STATE_SHUFFLE_OFF; updatePlayListRow(); } break; case MediaService.STATE_REPEAT_NONE: repeatAction.setIcon(ContextCompat.getDrawable(getActivity(), R.drawable.ic_repeat_white_48dp)); break; case MediaService.STATE_REPEAT_ALL: repeatAction .setIcon(ContextCompat.getDrawable(getActivity(), R.drawable.ic_repeat_enable_white_48dp)); break; case MediaService.STATE_REPEAT_ONE: repeatAction.setIcon(ContextCompat.getDrawable(getActivity(), R.drawable.ic_repeat_one_white_48dp)); break; } } rowsAdapter.notifyArrayItemRangeChanged(rowsAdapter.indexOf(playbackControlsRow), 1); }
From source file:com.mylovemhz.simplay.MusicService.java
public boolean isPlaying() { int state = getPlaybackState().getState(); return state == PlaybackStateCompat.STATE_BUFFERING || state == PlaybackStateCompat.STATE_FAST_FORWARDING || state == PlaybackStateCompat.STATE_PLAYING || state == PlaybackStateCompat.STATE_REWINDING; }