Solution
The seekToMillis(...)
method works after events within the YouTubePlayer.PlayerStateChangeListener. Therefore, the saved instance state bundle can be passed into the inner class made for the PlayerStateChangeListener.
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentYoutubeDialogBinding.inflate(inflater, container, false)
val youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance()
youTubePlayerFragment.initialize(Auth.APP_API_ID, object : OnInitializedListener {
override fun onInitializationSuccess(provider: Provider, player: YouTubePlayer, wasRestored: Boolean) {
if (!wasRestored) {
youtubePlayer = player
player.setPlayerStateChangeListener(MyPlayerStateChangeListener(savedInstanceState))
player.setPlaybackEventListener(MyPlaybackEventListener())
player.loadVideo(arguments!!.getString(ITEM_ID))
player.play()
}
}
override fun onInitializationFailure(provider: Provider, result: YouTubeInitializationResult) {
// TODO: add log statement.
}
})
childFragmentManager.beginTransaction().replace(R.id.youtubePlayer, youTubePlayerFragment as Fragment).commit()
return binding.root
}
private inner class MyPlayerStateChangeListener(var savedInstanceState: Bundle?) : YouTubePlayer.PlayerStateChangeListener {
internal var playerState = "UNINITIALIZED"
override fun onLoading() {
playerState = "LOADING"
}
override fun onLoaded(videoId: String) {
playerState = String.format("LOADED %s", videoId)
}
override fun onAdStarted() {
playerState = "AD_STARTED"
}
override fun onVideoStarted() {
if (savedInstanceState != null) {
println("YT_CURRENT: " + savedInstanceState!!.getInt(YOUTUBE_CURRENT_TIME_KEY))
youtubePlayer.seekToMillis(savedInstanceState!!.getInt(YOUTUBE_CURRENT_TIME_KEY))
playerState = "VIDEO_STARTED"
}
}