android-serviceandroid-mediaplayerandroid-seekbarandroid-mediasessionmediabrowserservice

How do I call getDuration in mediaBrowserService from an Activity?


Earlier, using boundService this could be easily achieved. But with MediaBrowserService I can't access getDuration outside, without which I am unable to update the seekbar.


Solution

  • On the MediaBrowserService, when you're updating the MediaMetadata, add the duration of the current media.

    MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder();
    metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, track.durationMs);
    

    While on the client side, using MediaBrowserCompat you're able to connect to you MediaBrowserService and retrieve a MediaSessionCompat.Token. With the token you can then get a MediaSessionController from where you can get the MediaMetadataCompat that has information about the current media.

    int duration = (int) metadata.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
    

    The official documentation has an ok explanation on how this works a whole