2

My service extends the MediaBrowserService class and it responds to certain MediaController actions such as getMediaController().getTransportControls().onPlay(). However, I didn't find a way to "control" my service from a Widget, because the MediaController class isn't available from it. How can I communicate with my service?

1 Answers1

3

The recommended approach is to use a MediaButtonReceiver, which will forward commands to your MediaBrowserService, where you can then handle them by adding a call to MediaButtonReceiver.handleIntent() in your onStartCommand as per the documentation.

You can use the buildMediaButtonPendingIntent() to construct a PendingIntent for various media buttons (such as play, pause, etc), which can then be set on your widget's buttons with setOnClickPendingIntent()

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thanks for such a detailed answer. I still have one question, though. How can I track the session's state (current song metadata, playback state) from the app widget? – MisterCereal Oct 19 '16 at 16:04
  • There isn't a synchronous way to get that information, so you'd need to use a service to update your widget. Then that service can connect via a `MediaBrowser` and create a `MediaController` from the session token. – ianhanniballake Oct 19 '16 at 16:58
  • @ianhanniballake How do I get about with the service? Do I start the service on widget enable and stop it on disable? – Ishaan Mar 18 '17 at 14:36
  • @Ishaan - that's not how a `MediaBrowserService` works, no. I'd suggest reading the [documentation on building a `MediaBrowserService`](https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html). `MediaButtonReceiver` does the correct thing to trigger the correct [Media Session Callback](https://developer.android.com/guide/topics/media-apps/audio-app/mediasession-callbacks.html) – ianhanniballake Mar 18 '17 at 23:59
  • @ianhanniballake Thanks for the reply but I wasn't referring to MediaBrowserService. You've suggested that I need to use a service to update the widget and connect with the MediaBrowser. It was this service that I was referring to. – Ishaan Mar 19 '17 at 01:35
  • @Ishaan - 'that service' should be your `MediaBrowserService` - the service that knows about your playback state can update the widget directly as it updates its other state (its MediaSession, notification, etc). – ianhanniballake Mar 19 '17 at 01:42
  • @ianhanniballake Thanks I understood. I am sorry I was getting confused since I am still new to MediaBrowserService. – Ishaan Mar 19 '17 at 15:50