Skip to content

Instantly share code, notes, and snippets.

@devrath
Created November 8, 2021 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devrath/f8eb832c432a28fab866cd6350e2452e to your computer and use it in GitHub Desktop.
Save devrath/f8eb832c432a28fab866cd6350e2452e to your computer and use it in GitHub Desktop.
How to call the periodic callback of progress of Exo player
binding.playerView.player?.addListener(object : Player.Listener { // player listener
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) { // check player play back state
Player.STATE_READY -> {
MLogger.d(TAG,"Stream is loaded into Exoplayer")
callback?.onStreamLoaded(true)
}
}
}
})
class ProgressJobTracker(
private val player: Player,
private val positionListener: PositionListener,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
) {
companion object {
const val PROGRESS_TRACK_DURATION : Long = 1000
}
private val coroutineContext = CoroutineScope(ioDispatcher + SupervisorJob())
interface PositionListener {
fun progress(position: Long)
}
init {
start()
}
fun start() {
coroutineContext.launch {
launchPeriodicAsync(PROGRESS_TRACK_DURATION) {
launch {
val result = withContext(Dispatchers.Main) {
return@withContext player.currentPosition
}
positionListener.progress(result)
}
}.join()
}
}
private fun CoroutineScope.launchPeriodicAsync(
repeatMillis: Long,
action: () -> Unit
) = this.launch {
if (repeatMillis > 0) {
while (isActive) { action()
delay(repeatMillis)
}
} else { action() }
}
fun purgeHandler() {
coroutineContext.cancel()
}
}
class ProgressTracker(private val player: Player, private val positionListener: PositionListener) : Runnable {
interface PositionListener {
fun progress(position: Long)
}
private val handler: Handler = Handler()
override fun run() {
val position = player.currentPosition
positionListener.progress(position)
handler.postDelayed(this, 1000)
}
fun purgeHandler() {
handler.removeCallbacks(this)
}
init {
handler.post(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment