Skip to content Skip to sidebar Skip to footer

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:

  1. Create a MediaControllerCompat from your MediaBrowserCompat instance, following the documentation
  2. Call sendCommand, passing in a command String which uniquely identifies your command (say, doMagic), any parameters you wish to pass to the method, and a ResultReceiver if you want a return value.
  3. In the MediaSessionCompat.Callback registered with your MediaBrowserServiceCompat, override onCommand() and handle the command (say, by calling doMagic).

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?"