I want to know what song is currently played on my Android phone. In the past, the solution would be to add an IntentFilter but now the solution should be based on MediaSession. Each media app posts its MediaSession. I have a the following listener:
private val mSessionsChangedListener =
MediaSessionManager.OnActiveSessionsChangedListener { list: List<MediaController>? ->
//...here
}
This listener fires every time a change in the active sessions occur. Then I can utilise MediaMetadata in order to grab the info about the currently playing song. In case there is only 1 active MediaSession, that works. However in case there are multiple apps with active sessions, I'm not sure how to determine which one of the List<MediaController> is actually playing.
I tried checking the playbackState like this:
list.forEach {
if (it.playbackState?.state == PlaybackState.STATE_PLAYING) {
currentMediaController = it
}
}
But when switching between 2 media apps, the playbackState is not updated yet when this listener is triggered.
What is the correct way of determining which MediaController is actually playing?
Thanks!
I think maybe something like the following might work:
This code iterates over all the
MediaControllersin the list and checks theirPlaybackState. If aMediaControllerhas aPlaybackStatethat is newer than the previousPlaybackStateseen, it becomes the new "latest"PlaybackState, and the correspondingMediaControllerbecomes the newlatestMediaController. If thePlaybackStateindicates that the media is playing,latestMediaControlleris updated accordingly.Note that this code assumes that each
MediaControllerhas a uniquePlaybackStateobject. If twoMediaControllershave the samePlaybackStateobject (i.e., they are both playing the same media), this code may not work correctly. In that case, you could use other criteria (such as the package name of theMediaController) to determine which one is actually playing. cg