我有这个媒体播放器,其他一切正常,我开始播放歌曲,它通过 2 个状态,最后一个是PlaybackStateCompat.STATE_PLAYING
因此我们可以说回调是注册的。问题是每当我触发 SeekBar 侦听器时,该方法seekTo
都不会触发,onPlaybackStateChanged
并且因为这没有发生,所以我无法将 SeekBar 更新为其新进度。这仅涉及 UI。音乐实际上是从修改 SeekBar 进度后的进度播放的。更重要的是,trackDurationTextView 也没有得到更新。当我在搜索栏上拖动拇指时,它会改变它的值,但是一旦我松开它,它就会进入它的初始进度,与搜索栏相同。
这是注册回调的地方。
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
if (service instanceof MediaPlayerService.ServiceBinder) {
try {
mediaController = new MediaControllerCompat(this, ((MediaPlayerService.ServiceBinder) service).getService().getMediaSessionToken());
} catch (RemoteException e) {
e.printStackTrace();
}
mediaController.registerCallback(mMediaControllerCallback);
}
}
这是回调的初始化方式:
private MediaControllerCompat.Callback mMediaControllerCallback = new MediaControllerCompat.Callback() {
@Override
public void onPlaybackStateChanged(@NonNull PlaybackStateCompat state) {
updatePlaybackState(state);
}
@Override
public void onMetadataChanged(MediaMetadataCompat metadata) {
if (metadata != null) {
updateMediaDescription(metadata.getDescription());
updateDuration(metadata);
}
}
};
这是OnSeekBarChangeListener
trackSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
trackDurationTextView.setText(DateUtils.formatElapsedTime(progress / 1000));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
stopSeekbarUpdate();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//TODO: look here! the seek bar position is not kept when the user slides it!
mediaController.getTransportControls().seekTo(seekBar.getProgress());
scheduleSeekBarUpdate();
}
});
private void updateProgress() {
if (mLastPlaybackState == null) {
return;
}
long currentPosition = mLastPlaybackState.getPosition();
if (mLastPlaybackState.getState() != PlaybackStateCompat.STATE_PAUSED) {
// Calculate the elapsed time between the last position update and now and unless
// paused, we can assume (delta * speed) + current position is approximately the
// latest position. This ensure that we do not repeatedly call the getPlaybackState()
// on MediaControllerCompat.
long timeDelta = SystemClock.elapsedRealtime() -
mLastPlaybackState.getLastPositionUpdateTime();
currentPosition += (int) timeDelta * mLastPlaybackState.getPlaybackSpeed();
}
trackSeekBar.setProgress((int) currentPosition);
}
这是在搜索栏更新后 mLastPlayBackState.getPosition 应该返回新值的地方,但它始终返回 0,因为永远不会调用 onPlaybackStateChanged。任何想法为什么?