How To Access Instance Of MediaBrowserServiceCompat Service?
I'm surprisingly struggling to get hold of the instance of a service which is derived from MediaBrowserServiceCompat. For a typical service, to achieve that, a local binder is used
Solution 1:
As you discovered, MediaBrowserServiceCompat
is already a bound service - you cannot and should not override onBind()
.
Instead, you must connect to your MediaBrowserServiceCompat
with a MediaBrowserCompat
as per the documentation. Once connected, you can trigger custom methods, like doMagic
by:
- Create a
MediaControllerCompat
from yourMediaBrowserCompat
instance, following the documentation - Call
sendCommand
, passing in acommand
String which uniquely identifies your command (say,doMagic
), any parameters you wish to pass to the method, and aResultReceiver
if you want a return value. - In the
MediaSessionCompat.Callback
registered with yourMediaBrowserServiceCompat
, override onCommand() and handle the command (say, by callingdoMagic
).
An example of this approach was offered in this blog post
Solution 2:
You can try this solution (for a quick fix, not recommend):
private final MyBinder myBinder = new MyBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
if (intent.getBooleanExtra("is_binding", false)) {
return myBinder;
}
return super.onBind(intent);
}
// Bind service in your activity:
Intent intent = new Intent(this, MyPlaybackService.class);
intent.putExtra("is_binding", true);
bindService(intent, this, Context.BIND_AUTO_CREATE);
Post a Comment for "How To Access Instance Of MediaBrowserServiceCompat Service?"