下面列出了android.media.session.PlaybackState#STATE_PLAYING 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
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);
}
}
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);
}
}
@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);
}
@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);
}
private PlaybackState getStateWithUpdatedPosition() {
PlaybackState state;
long duration = -1;
synchronized (mLock) {
state = mPlaybackState;
if (mMetadata != null && mMetadata.containsKey(MediaMetadata.METADATA_KEY_DURATION)) {
duration = mMetadata.getLong(MediaMetadata.METADATA_KEY_DURATION);
}
}
PlaybackState result = null;
if (state != null) {
if (state.getState() == PlaybackState.STATE_PLAYING
|| state.getState() == PlaybackState.STATE_FAST_FORWARDING
|| state.getState() == PlaybackState.STATE_REWINDING) {
long updateTime = state.getLastPositionUpdateTime();
long currentTime = SystemClock.elapsedRealtime();
if (updateTime > 0) {
long position = (long) (state.getPlaybackSpeed()
* (currentTime - updateTime)) + state.getPosition();
if (duration >= 0 && position > duration) {
position = duration;
} else if (position < 0) {
position = 0;
}
PlaybackState.Builder builder = new PlaybackState.Builder(state);
builder.setState(state.getState(), position, state.getPlaybackSpeed(),
currentTime);
result = builder.build();
}
}
}
return result == null ? state : result;
}
private void updatePlaybackState(String error) {
long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
if (playingMessageObject != null) {
position = playingMessageObject.audioProgressSec * 1000;
}
PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
int state;
if (playingMessageObject == null) {
state = PlaybackState.STATE_STOPPED;
} else {
if (MediaController.getInstance().isDownloadingCurrentMessage()) {
state = PlaybackState.STATE_BUFFERING;
} else {
state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
}
}
if (error != null) {
stateBuilder.setErrorMessage(error);
state = PlaybackState.STATE_ERROR;
}
stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
if (playingMessageObject != null) {
stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
} else {
stateBuilder.setActiveQueueItemId(0);
}
mediaSession.setPlaybackState(stateBuilder.build());
}
@Override
public void onStop() {
if (playerState == PlaybackState.STATE_PLAYING) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
resumePlayback();
}
}, 200);
}
super.onStop();
}
@Override
public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
super.onUnhandledKeyEvent(view, event);
if (event.getAction() == KeyEvent.ACTION_UP) {
if (warningScreenOpen && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
onReadyToExitSafetyInstructions(null);
} else {
if (webView.isVideoFullscreen()) {
if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_UP) {
showToolbar();
showCornerControls();
cornerControls.requestFocus(View.FOCUS_UP);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_DOWN) {
cornerControls.clearFocus();
hideToolbar();
hideCornerControls(true);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER) {
if (playerState == PlaybackState.STATE_PLAYING) {
webView.pauseVideo();
} else {
webView.playVideo();
}
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT) {
webView.seekBySeconds(+10);
} else if (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT) {
webView.seekBySeconds(-10);
}
}
}
}
}
private void updatePlaybackState(String error) {
long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
if (playingMessageObject != null) {
position = playingMessageObject.audioProgressSec * 1000L;
}
PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
int state;
if (playingMessageObject == null) {
state = PlaybackState.STATE_STOPPED;
} else {
if (MediaController.getInstance().isDownloadingCurrentMessage()) {
state = PlaybackState.STATE_BUFFERING;
} else {
state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
}
}
if (error != null) {
stateBuilder.setErrorMessage(error);
state = PlaybackState.STATE_ERROR;
}
stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
if (playingMessageObject != null) {
stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
} else {
stateBuilder.setActiveQueueItemId(0);
}
mediaSession.setPlaybackState(stateBuilder.build());
}
@Override
public void onPlaybackStateChanged(@NonNull PlaybackState state) {
super.onPlaybackStateChanged(state);
byte[] data = new byte[1];
data[0] = (byte)(state.getState() == PlaybackState.STATE_PLAYING ? 1 : 0);
mDevice.write(mediaPlayingCharac, data, MediaService.this);
}
/**
* 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();
}
}
private void updatePlaybackState(String error) {
long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
if (playingMessageObject != null) {
position = playingMessageObject.audioProgressSec * 1000L;
}
PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(getAvailableActions());
int state;
if (playingMessageObject == null) {
state = PlaybackState.STATE_STOPPED;
} else {
if (MediaController.getInstance().isDownloadingCurrentMessage()) {
state = PlaybackState.STATE_BUFFERING;
} else {
state = MediaController.getInstance().isMessagePaused() ? PlaybackState.STATE_PAUSED : PlaybackState.STATE_PLAYING;
}
}
if (error != null) {
stateBuilder.setErrorMessage(error);
state = PlaybackState.STATE_ERROR;
}
stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
if (playingMessageObject != null) {
stateBuilder.setActiveQueueItemId(MediaController.getInstance().getPlayingMessageObjectNum());
} else {
stateBuilder.setActiveQueueItemId(0);
}
mediaSession.setPlaybackState(stateBuilder.build());
}
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());
}
/**
* 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();
}
}
/**
* 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();
}
}
/**
* {@inheritDoc}
*/
public void sendMediaAction(int action) {
if (mMediaController == null) {
// Maybe somebody is waiting to start his player by
// this lovely event.
// TODO: Check if it works as expected.
MediaController2.broadcastMediaAction(mContext, action);
return;
}
MediaController.TransportControls controls = mMediaController.getTransportControls();
switch (action) {
case ACTION_PLAY_PAUSE:
if (mPlaybackState == PlaybackState.STATE_PLAYING) {
controls.pause();
} else {
controls.play();
}
break;
case ACTION_STOP:
controls.stop();
break;
case ACTION_SKIP_TO_NEXT:
controls.skipToNext();
break;
case ACTION_SKIP_TO_PREVIOUS:
controls.skipToPrevious();
break;
default:
throw new IllegalArgumentException();
}
}
public void registerActiveSessionCallback(Context context, List<MediaController> controllers) {
if (controllers.size() > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
controller = controllers.get(0);
sController = new WeakReference<>(controller);
if (controllerCallback != null) {
for (MediaController ctlr : controllers)
ctlr.unregisterCallback(controllerCallback);
} else {
controllerCallback = new MediaController.Callback() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onPlaybackStateChanged(PlaybackState state) {
super.onPlaybackStateChanged(state);
if (state == null)
return;
if (isInvalidPackage(controller))
return;
boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
if (!isPlaying) {
NotificationManager notificationManager =
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
notificationManager.cancel(0);
notificationManager.cancel(8);
}
savePlayerName(controller.getPackageName(), context);
if (controller != controller)
return; //ignore inactive sessions
broadcastControllerState(context, controller, isPlaying);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onMetadataChanged(MediaMetadata metadata) {
super.onMetadataChanged(metadata);
if (controller != controller)
return;
if (metadata == null)
return;
if (isInvalidPackage(controller))
return;
savePlayerName(controller.getPackageName(), context);
broadcastControllerState(context, controller, null);
}
};
}
controller.registerCallback(controllerCallback);
if (isInvalidPackage(controller))
return;
broadcastControllerState(context, controller, null);
}
}
public void update(MediaMetadata metadata, PlaybackState state, MediaSession.Token token) {
if (state == null || state.getState() == PlaybackState.STATE_STOPPED ||
state.getState() == PlaybackState.STATE_NONE) {
mService.stopForeground(true);
try {
mService.unregisterReceiver(this);
} catch (IllegalArgumentException ex) {
// ignore receiver not registered
}
mService.stopSelf();
return;
}
if (metadata == null) {
return;
}
boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
Notification.Builder notificationBuilder = new Notification.Builder(mService);
MediaDescription description = metadata.getDescription();
notificationBuilder
.setStyle(new Notification.MediaStyle()
.setMediaSession(token)
.setShowActionsInCompactView(0, 1, 2))
.setColor(mService.getApplication().getResources().getColor(R.color.notification_bg))
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(createContentIntent())
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setLargeIcon(MusicLibrary.getAlbumBitmap(mService, description.getMediaId()))
.setOngoing(isPlaying)
.setWhen(isPlaying ? System.currentTimeMillis() - state.getPosition() : 0)
.setShowWhen(isPlaying)
.setUsesChronometer(isPlaying);
// If skip to next action is enabled
if ((state.getActions() & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
notificationBuilder.addAction(mPrevAction);
}
notificationBuilder.addAction(isPlaying ? mPauseAction : mPlayAction);
// If skip to prev action is enabled
if ((state.getActions() & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
notificationBuilder.addAction(mNextAction);
}
Notification notification = notificationBuilder.build();
if (isPlaying && !mStarted) {
mService.startService(new Intent(mService.getApplicationContext(), MusicService.class));
mService.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
} else {
if (!isPlaying) {
mService.stopForeground(false);
mStarted = false;
}
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
public void update(MediaMetadata metadata, PlaybackState state, MediaSession.Token token) {
if (state == null || state.getState() == PlaybackState.STATE_STOPPED ||
state.getState() == PlaybackState.STATE_NONE) {
mService.stopForeground(true);
try {
mService.unregisterReceiver(this);
} catch (IllegalArgumentException ex) {
// ignore receiver not registered
}
mService.stopSelf();
return;
}
if (metadata == null) {
return;
}
boolean isPlaying = state.getState() == PlaybackState.STATE_PLAYING;
Notification.Builder notificationBuilder = new Notification.Builder(mService);
MediaDescription description = metadata.getDescription();
notificationBuilder
.setStyle(new Notification.MediaStyle()
.setMediaSession(token)
.setShowActionsInCompactView(0, 1, 2))
.setColor(mService.getApplication().getResources().getColor(R.color.notification_bg))
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentIntent(createContentIntent())
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setLargeIcon(MusicLibrary.getAlbumBitmap(mService, description.getMediaId()))
.setOngoing(isPlaying)
.setWhen(isPlaying ? System.currentTimeMillis() - state.getPosition() : 0)
.setShowWhen(isPlaying)
.setUsesChronometer(isPlaying);
// If skip to next action is enabled
if ((state.getActions() & PlaybackState.ACTION_SKIP_TO_PREVIOUS) != 0) {
notificationBuilder.addAction(mPrevAction);
}
notificationBuilder.addAction(isPlaying ? mPauseAction : mPlayAction);
// If skip to prev action is enabled
if ((state.getActions() & PlaybackState.ACTION_SKIP_TO_NEXT) != 0) {
notificationBuilder.addAction(mNextAction);
}
Notification notification = notificationBuilder.build();
if (isPlaying && !mStarted) {
mService.startService(new Intent(mService.getApplicationContext(), MusicService.class));
mService.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
} else {
if (!isPlaying) {
mService.stopForeground(false);
mStarted = false;
}
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}