Created
December 5, 2022 10:22
-
-
Save alokomkar/af75f195dfe2ed532e5628e2346ff03f to your computer and use it in GitHub Desktop.
AudioLoopBoundService
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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