Search code examples
androidkotlinmetadatamediasession

Android - How to update MediaSession Metadata so song changes are reflected on bluetooth connected device?


I am using this to set metadata once the player is started. That works great.

mediaSession.setMetadata(
                MediaMetadataCompat.Builder()
                    .putString(MediaMetadata.METADATA_KEY_ARTIST, Variables.currentArtist)
                    .putString(MediaMetadata.METADATA_KEY_TITLE, Variables.currentSong)
                    .build()
            )

When the stream starts playing, the track information is shown on the screen of the bluetooth device connected whether it's an Echo Show or my car's infotainment system. But, once the next song plays, it does not update. I have to stop/start the stream for it to update. How can I push updates to metadata without having to stop/start the playback? I am using this call with a handler every 5 seconds:

updateMetadata()

Which calls this function:

private fun updateMetadata() {
    val largeIcon =
        BitmapFactory.decodeResource(resources, com.rustfm.rustfm.R.drawable.album_art)
    mediaSession.setMetadata(
        MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, Variables.currentArtist)
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, Variables.currentSong)
            .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_DESCRIPTION, "Test Description")
            .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, largeIcon)
            .build()
    )
}

Every time I call that updateMetadata() function, my callback class is fired but I am not sure where to go from here. Any help or guidance is appreciated!

This is my call back class:

private inner class MediaControllerCallback : MediaControllerCompat.Callback() {

    override fun onMetadataChanged(metadata: MediaMetadataCompat?) {

        // Where to go from here?
        Log.d("Event Metadata", "Fired")
    }
}

Solution

  • Well if anyone reads this that has the same problem, my ENTIRE issue was that I wasn't setting the playback state at all in the code. Whoops. The moment I assigned a PlaybackStateCompat to my MediaSession, metadata started displaying and updating properly. I somehow totally forgot to set that.