Решение
Метод seekToMillis(...)
работает после событий в YouTubePlayer.PlayerStateChangeListener .Поэтому сохраненный пакет состояния экземпляра можно передать во внутренний класс, созданный для 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"
}
}