How can I use a MediaBrowserService with a widget?

2019-06-06 10:15发布

问题:

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:

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()