Skip to content

Instantly share code, notes, and snippets.

@alokomkar
Created December 5, 2022 10:22
Show Gist options
  • Save alokomkar/af75f195dfe2ed532e5628e2346ff03f to your computer and use it in GitHub Desktop.
Save alokomkar/af75f195dfe2ed532e5628e2346ff03f to your computer and use it in GitHub Desktop.
AudioLoopBoundService
import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import com.alokomkar.javacollections.R
class AudioLoopBoundService: Service() {
private val binder: AudioLoopServiceBinder by lazy {
AudioLoopServiceBinder()
}
private var mediaPlayer: MediaPlayer? = null
override fun onBind(intent: Intent?): IBinder {
return binder
}
fun runAction(action: ServiceAction) {
when(action) {
ServiceAction.START_ACTION -> startPlayback()
ServiceAction.STOP_ACTION -> stopPlayback()
}
}
private fun startPlayback() {
initializePlayer()
mediaPlayer?.apply {
isLooping = true
start()
}
}
private fun stopPlayback() = mediaPlayer?.stop()
private fun initializePlayer() {
mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio)
}
inner class AudioLoopServiceBinder: Binder() {
fun getService(): AudioLoopBoundService = this@AudioLoopBoundService
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment