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.

New contributor

Пенка Пшеничная is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật