Skip to content
This repository was archived by the owner on Jul 16, 2024. It is now read-only.

Commit 27aa6d4

Browse files
authored
Cleanup AudioPlayService (#281)
Separated from #280.
1 parent dee13cd commit 27aa6d4

File tree

2 files changed

+8
-10
lines changed

2 files changed

+8
-10
lines changed

base/src/main/kotlin/io/goooler/demoapp/base/util/BaseExtensions.kt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,8 @@ fun Context.setMusicMute(mute: Boolean = true) {
531531
}
532532
}
533533

534+
inline fun <reified T : Any> Context.requireSystemService(): T = checkNotNull(getSystemService())
535+
534536
// ---------------------Activity-------------------------------//
535537

536538
@MainThread

common/src/main/kotlin/io/goooler/demoapp/common/service/AudioPlayService.kt

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,18 @@ import android.media.AudioAttributes
66
import android.media.AudioManager
77
import android.media.MediaPlayer
88
import android.os.Build
9-
import androidx.core.content.getSystemService
109
import io.goooler.demoapp.base.core.BaseService
10+
import io.goooler.demoapp.base.util.requireSystemService
1111
import io.goooler.demoapp.base.util.unsafeLazy
1212

1313
class AudioPlayService : BaseService() {
1414

1515
private val mediaPlayer = MediaPlayer()
1616
private var lastStreamUrl = ""
17-
private var audioManager: AudioManager? = null
17+
private val audioManager: AudioManager by unsafeLazy { requireSystemService() }
1818

1919
override val contentTitle: String get() = "正在播放音频"
2020

21-
override fun onCreate() {
22-
super.onCreate()
23-
audioManager = getSystemService()
24-
}
25-
2621
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
2722
when (intent?.action) {
2823
PAUSE -> pausePlay()
@@ -69,20 +64,21 @@ class AudioPlayService : BaseService() {
6964

7065
private fun stopPlay() {
7166
abandonAudioFocus()
72-
audioManager = null
7367
mediaPlayer.stop()
7468
}
7569

7670
private fun requestAudioFocus() {
77-
audioManager?.requestAudioFocus(
71+
@Suppress("DEPRECATION")
72+
audioManager.requestAudioFocus(
7873
audioFocusChangeListener,
7974
AudioManager.STREAM_MUSIC,
8075
AudioManager.AUDIOFOCUS_GAIN,
8176
)
8277
}
8378

8479
private fun abandonAudioFocus() {
85-
audioManager?.abandonAudioFocus(audioFocusChangeListener)
80+
@Suppress("DEPRECATION")
81+
audioManager.abandonAudioFocus(audioFocusChangeListener)
8682
}
8783

8884
private val audioFocusChangeListener by unsafeLazy {

0 commit comments

Comments
 (0)