How to stop MediaBrowserServiceCompat?

2.2k Views Asked by At

My service:

public class MusicService extends MediaBrowserServiceCompat {
...
}

My Activity:

public class MediaActivity extends AppCompatActivity{
private MediaBrowserCompat mMediaBrowser;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMediaBrowser = new MediaBrowserCompat(this,
                new ComponentName(this, MusicService.class), mConnectionCallback, null);
        mMediaBrowser.connect();
}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaBrowser.disconnect();
    }

I want to add button close in UI, but how to stop MusicService? It continues casting in background.

2

There are 2 best solutions below

1
On

I've declared a method in MediaSessionConnection:


    class MediaSessionConnection(
        val context: Context,
        private val serviceComponent: ComponentName
    ) {
      ...
      fun release() {
        mediaBrowser.disconnect()
        mediaController.sendCommand("disconnect", null, null)
      }
      ...
    }

And in MusicService:


    class MusicService : MediaBrowserServiceCompat() {

        override fun onCreate() {
            super.onCreate()
            ...
            mediaSessionConnector = MediaSessionConnector(mediaSession, object : DefaultPlaybackController() {
              override fun onCommand(player: Player?, command: String?, extras: Bundle?, cb: ResultReceiver?) {
                if (command == "disconnect") {
                  stopForeground(true)
                  stopSelf()
                }
              }

              override fun getCommands(): Array {
                return arrayOf("disconnect")
              }
            })
        }
    }

I do not claim, that this is the correct way of stopping the service completely, but this is the solution that I've came up to after struggling some hours.

If mediaBrowser.disconnect() is not executed, then stopSelf() won't destroy the service (by telling "destroy the service" I anticipate onDestroy() to be called).

Without explicitly performing stopForeground() and stopSelf() simply performing mediaBrowser.disconnect() wouldn't destroy the service.

0
On

To stop from anywhere: getActivity().stopService(new Intent(getActivity().getApplicationContext(), YourServiceName.class));