Play / Pause YoutubePlayer programmatically after resuming background work

My app has activity A for playing Youtube videos (using YoutubePlayerFragment). In this step, A has its own button B to control playback. When an activity is loading and playing a video, I can use the B button to control playback. Then click the "Home" button. When I resume action A from the recent task menu, button B no longer works. I can only play videos from its own play button (inside YoutubePlayerFragment). I am currently storing an instance of YoutubePlayer when called onInitializationSuccess:

private val onInitializedListener = object : YouTubePlayer.OnInitializedListener {
    override fun onInitializationSuccess(provider: YouTubePlayer.Provider, youTubePlayer: YouTubePlayer, wasRestored: Boolean) {
        Log.d(DEBUG_TAG, "YoutubePlayer - onInitializationSuccess")
        if (!wasRestored) {
            mYoutubePlayer = youTubePlayer
            mYoutubePlayer!!.setPlayerStateChangeListener(playerStateChangeListener)
            mYoutubePlayer!!.setPlaybackEventListener(mPlaybackEventListener)
            mYoutubePlayer!!.setShowFullscreenButton(false)
            mYoutubePlayer!!.loadVideo(mCurrentVideoId)
        } else {
            Log.d(DEBUG_TAG, "Restored from a previously saved state")
        }
    }

    override fun onInitializationFailure(provider: YouTubePlayer.Provider, youTubeInitializationResult: YouTubeInitializationResult) {
        if (youTubeInitializationResult.isUserRecoverableError) {
            youTubeInitializationResult.getErrorDialog(this@KActivityPlayVideo, 1).show()
        } else {
            Toast.makeText(this@KActivityPlayVideo,
                    "Failed to initialize video, please try again!",
                    Toast.LENGTH_LONG).show()
        }
    }
}

B YoutubePlayer Play/Pause . A , . - , , ? .

+4
1

, .

private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {

    @Override
    public void onPlaying() {
        // Called when playback starts, either due to user action or call to play().

    }

    @Override
    public void onPaused() {
        // Called when playback is paused, either due to user action or call to pause().

    }

    @Override
    public void onStopped() {
        // Called when playback stops for a reason other than being paused.

    }

    @Override
    public void onBuffering(boolean b) {
        // Called when buffering starts or ends.
    }

    @Override
    public void onSeekTo(int i) {
        // Called when a jump in playback position occurs, either
        // due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
    }
}
-1

Source: https://habr.com/ru/post/1662663/


All Articles