How to Handle YouTube Fragment OnSaveInstanceState
Asked Answered
B

1

0

Issue

The YouTube documentation does not clearly outline where to call seekToMillis() in the YouTube lifecycle of their API guide or documentation for Android.

In order to make sure the YouTube player picks up from where it left of when the screen is rotated seekToMillis(...) is required. However, this method does not work as expected being called directly before or after loadVideo(...) or play().

Expected

Call seekToMillis(...) to start video at specific point in milliseconds.

Bunton answered 24/9, 2018 at 14:39 Comment(0)
B
0

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"
        }
    }
Bunton answered 24/9, 2018 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.