How to play sound from Glance widget using MediaSessionService

I'm trying to write an app that allows audio to be launched from an app and widget using Jetpack Compose and Glance Widgets. The app shows all audio from the device, which can be controlled (start and stop), and added to the widget to play and stop it from the widget. Requires the display of running audio to be synchronized, meaning that when audio is started from the app, the widget will update and the play icon will change, and if the audio is started or stopped from the widget, those changes can be seen in the app.

I implemented AppWidget like this. I pass the link of the playing sound (the link can be null, which means stop playing) through DataStore preferences. Sounds added to the widget I get from Room DB via repository.

override suspend fun provideGlance(context: Context, id: GlanceId) {
        val playingSoundUrlStream = context.dataStore.data.map { prefs ->
            prefs[PLAYING_SOUND_URL_DATASTORE_KEY] ?: ""
        }
        provideContent {
            val soundRepository =
                remember { OfflineSoundRepository.get(context.applicationContext) }
            val playingSoundUrl = playingSoundUrlStream.collectAsState(initial = "").value
            GlanceTheme {
                AudiotWidgetView(
                    repository = soundRepository,
                    playingSoundUrl = playingSoundUrl,
                    onSoundPlayStopClicked = {
                    }
                )
            }
        }
    }

I also implemented SoundServiceHandler, which contains the player state via MutableStateFlow: if isPlaying = true, the id and track name are passed, if = false, the state is Stopped.

class SoundServiceHandler @Inject constructor(
    @ApplicationContext private val context: Context,
    private val mediaSession: MediaSession
) : Player.Listener {
    init {
        mediaSession.player.addListener(this)
    }
    private val _serviceState = MutableStateFlow<PlayerState>(PlayerState.Initial)
    val serviceState = _serviceState.asStateFlow()
...
override fun onIsPlayingChanged(isPlaying: Boolean) {
        WidgetWorker.enqueue(context, if (isPlaying) mediaSession.player.currentMediaItem?.mediaId else null)
        if (!isPlaying) _serviceState.update { PlayerState.Stopped }
        super.onIsPlayingChanged(isPlaying)
    }

In the same SoundServiceHandler I made a method that sets and plays the sound, and stops playback.

In the onIsPlayingChanged method, I call the Worker job to update the widget in the background process: set the url of the sound and call AppWidget().updateAll() to have the changes accepted.

val soundUrl: String = inputData.getString(PLAYING_SOUND_URL_KEY) ?: ""
        applicationContext.dataStore.edit { settings ->
            settings[PLAYING_SOUND_URL_DATASTORE_KEY] = soundUrl
        }
        AppWidget().updateAll(applicationContext)
       

So, I have sound playing and stopping, widget refreshing, showing info on the home screen, but I don't understand how to make the sound play from the widget. And, if I delete the application from TaskManager, the widget is not updated. I assume this is because Hilt provides ExoPlayer, but doesn't start the service that MediaSession provides.

The implementation of MediaSessionService is typical, as in the documentation: the onCreate, onTaskRemoved and onDestroy methods are implemented, as well as onGetSession.

Upvotes: 1

Views: 65

Answers (0)

Related Questions