How to access instance of MediaBrowserServiceCompat service?

时光毁灭记忆、已成空白 提交于 2019-12-04 19:35:33

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!