我正在使用此example code来构建MediaPlayer Service
。我或多或少都在工作,但是如果用户返回包含媒体控件的Activity
,我需要检测MediaPlayer
所处的状态。我正在使用的代码抛出一个NullReferenceException
中出现onResume
错误,因为getPlaybackState()
始终为null
。
我刚开始使用MediaSessionCompat
,根据文档,我可以以某种方式获得当前会话:
“创建会话后,会话的所有者可以将其会话令牌传递给其他进程,以允许他们创建MediaControllerCompat以与会话进行交互。”
public class MediaActivity extends AppCompatActivity {
private MediaBrowserCompat mMediaBrowserCompat;
private MediaControllerCompat mMediaControllerCompat;
private Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_media);
mActivity = this;
mPlayButton = (Button)findViewById(R.id.btn_play);
mMediaBrowserCompat = new MediaBrowserCompat(
getApplicationContext(),
new ComponentName(mContext, MediaPlayerService.class),
mMediaBrowserCompatConnectionCallback,
getIntent().getExtras()
);
mMediaBrowserCompat.connect();
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if( mCurrentState == STATE_PAUSED ) {
getSupportMediaController().getTransportControls().play();
mCurrentState = STATE_PLAYING;
mPlayButton.setText("Pause");
} else {
MediaControllerCompat.getMediaController(mActivity).getTransportControls().pause();
mCurrentState = STATE_PAUSED;
mPlayButton.setText("Play");
}
}
});
@Override
public void onResume() {
super.onResume();
if (MediaControllerCompat.getMediaController(mActivity).getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING) {
mPlayButton.setText("Pause")
}
else{
mPlayButton.setText("Play")
}
}
private MediaBrowserCompat.ConnectionCallback mMediaBrowserCompatConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
super.onConnected();
try {
mMediaControllerCompat = new MediaControllerCompat(PodcastEpisodeActivity.this, mMediaBrowserCompat.getSessionToken());
mMediaControllerCompat.registerCallback(mMediaControllerCompatCallback);
MediaControllerCompat.setMediaController(mActivity, mMediaControllerCompat);
MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromUri(Uri.parse("http://www.url.com"), extras);
} catch( RemoteException e ) {
Log.e(mActivity.getPackageName(), e.toString());
}
}
};
private MediaControllerCompat.Callback mMediaControllerCompatCallback = new MediaControllerCompat.Callback() {
@Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
super.onPlaybackStateChanged(state);
if (state == null ) return;
switch (state.getState()) {
case PlaybackStateCompat.STATE_PLAYING: {
mCurrentState = STATE_PLAYING;
break;
}
case PlaybackStateCompat.STATE_PAUSED: {
mCurrentState = STATE_PAUSED;
break;
}
}
}
};
}
}
答案 0 :(得分:0)
我无法通过可用的API找到方法,所以我只是通过本地存储(sqlite)跟踪正在播放的媒体,并通过它更新显示。可能不是最优雅的解决方案,但它有效。