Merge pull request #342 from qwertyfinger/fix-audio-focus

Don't remove MusicService from foreground on focus loss during playback
This commit is contained in:
Tibor Kaputa 2021-08-29 10:56:02 +02:00 committed by GitHub
commit 7af3378432
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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)