From c8fdb46dfc8a0b64078437b7ca4b07f75c81bbc3 Mon Sep 17 00:00:00 2001 From: Andrii Chubko Date: Sun, 29 Aug 2021 10:53:27 +0300 Subject: [PATCH] Don't remove MusicService from foreground on focus loss during playback Otherwise, our Service can be easily killed by the OS and playback won't be resumed when the focus should be gained back. --- .../musicplayer/services/MusicService.kt | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/src/main/kotlin/com/simplemobiletools/musicplayer/services/MusicService.kt b/app/src/main/kotlin/com/simplemobiletools/musicplayer/services/MusicService.kt index 9a5f7ad8..c97f13a6 100644 --- a/app/src/main/kotlin/com/simplemobiletools/musicplayer/services/MusicService.kt +++ b/app/src/main/kotlin/com/simplemobiletools/musicplayer/services/MusicService.kt @@ -15,10 +15,7 @@ import android.media.MediaPlayer import android.media.audiofx.Equalizer import android.media.session.PlaybackState.PLAYBACK_POSITION_UNKNOWN import android.net.Uri -import android.os.CountDownTimer -import android.os.Handler -import android.os.Looper -import android.os.PowerManager +import android.os.* import android.provider.MediaStore import android.provider.MediaStore.Audio import android.support.v4.media.MediaMetadataCompat @@ -136,6 +133,8 @@ class MusicService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnEr return START_NOT_STICKY } + notifyFocusGained() + val action = intent.action if (isOreoPlus() && action != NEXT && action != PREVIOUS && action != PLAYPAUSE) { setupFakeNotification() @@ -169,6 +168,11 @@ class MusicService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnEr return START_NOT_STICKY } + private fun notifyFocusGained() { + mWasPlayingAtFocusLost = false + mPrevAudioFocusState = AUDIOFOCUS_GAIN + } + private fun initService(intent: Intent?) { mTracks.clear() mCurrTrack = null @@ -477,7 +481,9 @@ class MusicService : Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnEr // delay foreground state updating a bit, so the notification can be swiped away properly after initial display Handler(Looper.getMainLooper()).postDelayed({ - if (!getIsPlaying()) { + val isFocusLost = mPrevAudioFocusState == AUDIOFOCUS_LOSS || mPrevAudioFocusState == AUDIOFOCUS_LOSS_TRANSIENT + val isPlaybackStoppedAfterFocusLoss = mWasPlayingAtFocusLost && isFocusLost + if (!getIsPlaying() && !isPlaybackStoppedAfterFocusLoss) { stopForeground(false) } }, 200L)