I'm trying to connect to a MediaBrowserService from an activity using a MediaBrowser. However, my onConnected
callback never seems to be called to allow me to set up the MediaController
and start manipulating playback.
In my player/browser activity:
private final MediaBrowserCompat.ConnectionCallback mConnectionCallback =
new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
try {
mMediaController =
new MediaControllerCompat(
PlayActivity.this,
mMediaBrowser.getSessionToken()
);
mMediaController.registerCallback(mControllerCallback);
mControllerCallback
.onMetadataChanged(mMediaController.getMetadata());
mControllerCallback
.onPlaybackStateChanged(mMediaController.getPlaybackState());
} catch (RemoteException e) {
throw new RuntimeException(e);
}
mMediaController
.getTransportControls()
.prepareFromUri(
Uri.parse(
getIntent()
.getStringExtra(StreamingService.STREAM_URI)),
getIntent().getExtras());
mMediaController
.getTransportControls().play();
buildTransportControls();
}
@Override
public void onConnectionSuspended() { }
@Override
public void onConnectionFailed() { }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
mMediaBrowser = new MediaBrowserCompat(this,
new ComponentName(this, StreamingService.class),
mConnectionCallback,
null);
}
@Override
public void onStart() {
super.onStart();
mMediaBrowser.connect();
}
I've added breakpoints with the debugger and it seems that execution does reach the service, to the end of its onCreate
method, but execution never seems to reach either the onConnected
or onConnectionFailed
methods of my connection callback. After connect
is called, checked isConnected
returns false.
I'm not sure how to debug further as the problem is happening somewhere during the connection process, and as far as I can tell my code conforms to Android example guides. And yes I am calling setSessionToken
in onCreate
of the browser service.
If I try to set up the MediaController in onStart
of my activity, after I call connect
, I get an exception stating that the browser is not connected and so the session token cannot be set. So although execution goes into onCreate
of my service, the connection is not completing.
I found the bug. I was overriding the following method in my StreamingService
(MediaBrowserServiceCompat
) class:
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
Removing the method completely allows the connection to take place.