这是我如何做到的。
首先初始化 MediaSessionCompat、MediaSessionConnector 和 MediaControllerCompat,如下所示。
private void initMediaSession(){
ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
mMediaSessionCompat = new MediaSessionCompat(getApplicationContext(), "MyMediasession", mediaButtonReceiver, null);
MediaSessionConnector mediaSessionConnector = new MediaSessionConnector(mMediaSessionCompat, mPlaybackController, false);
mediaSessionConnector.setPlayer(mMediaPlayerManager.getPlayer(), null);
mMediaControllerCompat = mMediaSessionCompat.getController();
}
在此 MediaSessionConnector.PlaybackController 中接收所有回调。
private MediaSessionConnector.PlaybackController mPlaybackController = new MediaSessionConnector.PlaybackController() {
@Override
public long getSupportedPlaybackActions(@Nullable Player player) {
long ACTIONS = PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY
| PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_STOP;
return ACTIONS;
}
@Override
public void onPlay(Player player) {
}
@Override
public void onPause(Player player) {
}
@Override
public void onSeekTo(Player player, long position) {
}
@Override
public void onFastForward(Player player) {
}
@Override
public void onRewind(Player player) {
}
@Override
public void onStop(Player player) {
}
};
现在您可以使用 MediaControllerCompat.TransportControls 在单击播放/暂停按钮时发送播放、暂停等事件。
mMediaControllerCompat.getTransportControls().play();//For play
mMediaControllerCompat.getTransportControls().pause();//For pause
在使用 TransportControls 方法时,MediaSessionConnector.PlaybackController 的相应方法也会同时被调用。