我遵循了关于连接 MediaBrowserCompat 的 Android 官方文档,但它被拒绝连接,事实上既没有onConnected()
,onConnectionSuspended()
也没有onConnectionFailed()
被调用。
我也试过这个答案,但没有奏效。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupMediaComponents();
// initializeViews();
}
private void setupMediaComponents() {
Log.d(TAG, "setupMediaComponents");
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaBrowserCompat = new MediaBrowserCompat(this, new ComponentName(this, SongPlayerService.class),
mediaBrowserCompatConnectionCallback, null);
}
@Override
protected void onStart() {
super.onStart();
mediaBrowserCompat.connect();
}
@Override
public void onStop() {
super.onStop();
// (see "stay in sync with the MediaSession")
if (MediaControllerCompat.getMediaController(this) != null) {
MediaControllerCompat.getMediaController(this).unregisterCallback(controllerCallback);
}
mediaBrowserCompat.disconnect();
}
private MediaBrowserCompat.ConnectionCallback mediaBrowserCompatConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
Log.d(TAG, "onConnected");
try {
// Create a MediaControllerCompat
MediaControllerCompat mediaController =
new MediaControllerCompat(AudioPlayerActivity.this, mediaBrowserCompat.getSessionToken());
// Save the controller
MediaControllerCompat.setMediaController(AudioPlayerActivity.this, mediaController);
setControlClickListeners();
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onConnectionSuspended() {
Log.d(TAG, "onConnectionSuspended");
// We were connected, but no longer :-(
}
@Override
public void onConnectionFailed() {
Log.d(TAG, "onConnectionFailed");
// The attempt to connect failed completely.
// Check the ComponentName!
}
};
我正在使用25.3.1
支持库的版本,并且所有 sdk 工具都是最新的。
编辑
SongPlayerService 的一部分
@Nullable
@Override
public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
// Returning null means no one can connect so we’ll return something
return new BrowserRoot(getString(R.string.app_name), null); // Name visible in Android auto, Bundle is for optional params
// TODO: Support Android auto
}