Skip to content
This repository was archived by the owner on Jan 9, 2026. It is now read-only.

Fix: keep isForegroundService flag in sync with service state#445

Merged
nic0lette merged 1 commit into
android:mainfrom
mhelder:issue-444-musicservice-stops-running-in-foreground-after-being-paused
Apr 8, 2021
Merged

Fix: keep isForegroundService flag in sync with service state#445
nic0lette merged 1 commit into
android:mainfrom
mhelder:issue-444-musicservice-stops-running-in-foreground-after-being-paused

Conversation

@mhelder
Copy link
Copy Markdown
Contributor

@mhelder mhelder commented Apr 8, 2021

This closes #444.

The local flag isForegroundService is currently only set to false when the notification is cancelled:

override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
stopForeground(true)
isForegroundService = false
stopSelf()
}

There is however another scenario that will stop the service from running in the foreground: when the player's playback state changes to paused (playWhenReady == false)

if (!playWhenReady) {
// If playback is paused we remove the foreground state which allows the
// notification to be dismissed. An alternative would be to provide a
// "close" button in the notification which stops playback and clears
// the notification.
stopForeground(false)
}

In this last scenario, isForegroundService is not set to false, which prevents it from being promoted to the foreground again when a notification update is posted:

if (ongoing && !isForegroundService) {
ContextCompat.startForegroundService(
applicationContext,
Intent(applicationContext, this@MusicService.javaClass)
)
startForeground(notificationId, notification)
isForegroundService = true
}
}

This PR adds that missing statement, allowing the service to be promoted to the foreground again when playback resumes.

For a more extensive description of the bug, see issue description.

…from the foreground because of playback state change
@nic0lette
Copy link
Copy Markdown
Contributor

Thank you!

@nic0lette nic0lette merged commit 8913b52 into android:main Apr 8, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MusicService stops running in foreground after being paused

2 participants