Tuesday, 28 March 2023

Android - How to determine which music app is currently playing?

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!



from Android - How to determine which music app is currently playing?

No comments:

Post a Comment