下面列出了怎么用android.media.session.PlaybackState的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
});
}
}
@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);
}
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;
}
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());
}
@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();
}
}
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);
}
}
@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());
}
});
}
@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 */
}
@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);
}
@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);
}
@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 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());
}
});
}
/**
* 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;
}
}
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 );
}
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());
}
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 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 */
}
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() {
if (mCallback == null) {
return;
}
PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
.setActions(getAvailableActions());
stateBuilder.setState(mState, getCurrentStreamPosition(), 1.0f, SystemClock.elapsedRealtime());
mCallback.onPlaybackStatusChanged(stateBuilder.build());
}
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();
}
private long getAvailableActions() {
long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID | PlaybackState.ACTION_PLAY_FROM_SEARCH;
MessageObject playingMessageObject = MediaController.getInstance().getPlayingMessageObject();
if (playingMessageObject != null) {
if (!MediaController.getInstance().isMessagePaused()) {
actions |= PlaybackState.ACTION_PAUSE;
}
actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
}
return actions;
}
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());
}
@Nullable
private MediaController pickBestMediaController(
@NonNull List<MediaController> list) {
int mediaControllerScore = -1;
MediaController mediaController = null;
for (MediaController mc : list) {
if (mc == null) continue;
int mcScore = 0;
// Check for the current state
PlaybackState state = mc.getPlaybackState();
if (state != null) {
switch (state.getState()) {
case PlaybackState.STATE_STOPPED:
case PlaybackState.STATE_ERROR:
break;
default:
mcScore++;
break;
}
}
if (mcScore > mediaControllerScore) {
mediaControllerScore = mcScore;
mediaController = mc;
}
}
return mediaController;
}
@Override
public boolean onResourceReady(Object resource, Object model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
albumNow = (Bitmap) resource;
mediaSession.setMetadata(new MediaMetadata.Builder()
.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, albumNow)
.putString(MediaMetadata.METADATA_KEY_ARTIST, singerNow)
.putString(MediaMetadata.METADATA_KEY_TITLE, titleNow)
.build());
PlaybackState.Builder stateBuilder = new PlaybackState.Builder();
stateBuilder.setState(PlaybackState.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1.0f);
mediaSession.setPlaybackState(stateBuilder.build());
buildNotification(MyConstant.playing);
return false;
}
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)));
}
public void stop() {
mState = PlaybackState.STATE_STOPPED;
updatePlaybackState();
// Give up Audio focus
mAudioManager.abandonAudioFocus(this);
// Relax all resources
releaseMediaPlayer();
}
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;
}
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());
}