Search code examples
androidyoutubeplayer

YouTubePlayerView stops on screen rotate


I am using YouTubePlayerView to load the video.The video plays successfully, but when the screen is rotated, the it stops playing.How do I overcome this problem?It may be a simple thing.I googled but didn't get help but your help is needed... Below is my code.

Code:

youTubePlayerView=findViewById(R.id.youtube_view);
        onInitializedListener=new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                youTubePlayers=youTubePlayer;
                youTubePlayers.loadVideo("9ZaEPeaucIU");
                youTubePlayers.setFullscreenControlFlags(FULLSCREEN_FLAG_CONTROL_ORIENTATION);
                youTubePlayers.setOnFullscreenListener(onFullscreenListener);
            }
            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                }
        };
        onFullscreenListener=new YouTubePlayer.OnFullscreenListener() {
            @Override
            public void onFullscreen(boolean b) {
                if (b){
                    time=youTubePlayers.getCurrentTimeMillis();


                }

            }
        };
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                youTubePlayerView.initialize("AI&*$^$^$3634HxbhVM@#$%%^%&%$",onInitializedListener);

                }
        });

Layout:

<com.google.android.youtube.player.YouTubePlayerView
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:id="@+id/youtube_view"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</com.google.android.youtube.player.YouTubePlayerView>

Solution

  • Add this on your activity declaration in AndroidManifext.xml so that, the activtiy doesn't recreate on orientation change.

    <activity
            android:name=".NameOfYourActivitiy"
            android:configChanges="orientation|screenSize">
    
    </activity>