'Save ExoPlayer position to continue playback after closing the view (onDestroy())
As I have understood, when I exit the player view while watching a video by pressing or not the pause button, the onPause() and onStop() methods come into play and if we pressing back button the onDestroy() method comes into play and destroy the view.
The following code achieves that when I leave the view of the player pressing or not to the pause button, for example to increase the brightness of the screen and I return to the video, the reproduction continues for where it was left. That's good for me. But when I press the back button and play the video again, it starts from the beginning.
I could control it in the onCreate() method, but I can't find the right key.
Any idea? Thank you
private lateinit var binding: ActivityExoPlayerPlayPeliBinding
private var player: ExoPlayer? = null
private var playWhenReady = true
private var currentItem = 0
private var playbackPosition: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityExoPlayerPlayPeliBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun onStart() {
super.onStart()
initializePlayer()
}
override fun onPause() {
super.onPause()
savePos()
}
override fun onStop() {
super.onStop()
savePos()
}
override fun onResume() {
super.onResume()
hideSystemUi()
continuePlayer(savePos())
}
override fun onDestroy() {
super.onDestroy()
savePos()
}
private fun savePos(): Long {
if (player != null){
playbackPosition = player!!.currentPosition
player!!.removeListener(this)
player!!.release()
player = null
}
return playbackPosition
}
private fun continuePlayer(playPosition: Long) {
player = ExoPlayer.Builder(applicationContext).build()
player!!.addListener(this)
binding.videoView.player = player
val url = intent.getStringExtra("url")
val mediaItem = item(url!!)
player!!.setMediaItem(mediaItem)
player!!.isCurrentMediaItemLive
playWhenReady
player!!.seekTo(currentItem, playPosition)
player!!.prepare()
player!!.play()
}
private fun initializePlayer() {
player = ExoPlayer.Builder(applicationContext).build()
player!!.addListener(this)
binding.videoView.player = player
val url = intent.getStringExtra("url")
val mediaItem = item(url!!)
player!!.setMediaItem(mediaItem)
player!!.isCurrentMediaItemLive
playWhenReady
player!!.seekTo(currentItem, playbackPosition)
player!!.prepare()
player!!.play()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
