Skip to content

Commit

Permalink
Stop the service in onTaskRemoved
Browse files Browse the repository at this point in the history
If the player isn't set to play when ready, the service is stopped and resources released.
 This is done because if the app is swiped away from recent apps without this check, the notification would remain in an unresponsive state.
Further explanation can be found at: androidx/media#167 (comment)
  • Loading branch information
PaulWoitaschek committed Jun 30, 2023
1 parent d579cf8 commit 625e59e
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions playback/src/main/kotlin/voice/playback/session/PlaybackService.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package voice.playback.session

import android.content.Intent
import androidx.media3.session.MediaLibraryService
import androidx.media3.session.MediaSession
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -32,12 +33,28 @@ class PlaybackService : MediaLibraryService() {
setMediaNotificationProvider(voiceNotificationProvider)
}

override fun onDestroy() {
super.onDestroy()
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
if (!player.playWhenReady) {
// If the player isn't set to play when ready, the service is stopped and resources released.
// This is done because if the app is swiped away from recent apps without this check,
// the notification would remain in an unresponsive state.
// Further explanation can be found at: https://github.com/androidx/media/issues/167#issuecomment-1615184728
release()
stopSelf()
}
}

private fun release() {
player.release()
session.release()
scope.cancel()
}

override fun onDestroy() {
super.onDestroy()
release()
}

override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession = session
}

0 comments on commit 625e59e

Please sign in to comment.