Created
November 8, 2021 14:52
-
-
Save devrath/f8eb832c432a28fab866cd6350e2452e to your computer and use it in GitHub Desktop.
How to call the periodic callback of progress of Exo player
This file contains 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
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) | |
} | |
} | |
} | |
}) |
This file contains 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
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() | |
} | |
} |
This file contains 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
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