I tried the project explained on this YouTube video of how to play YouTube videos on Android apps:
https://www.youtube.com/watch?v=Up9BjrIuoXY
I tried to play YouTube videos with devices using Android 9 and Android 10 and the videos are played correctly, but in Android 11 devices I received this message inside the YouTube video window:
"An error occurred while initializing the YouTube player".
This is the code of MainActivity.java:
package com.example.youtube;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity {
Button play_btn;
YouTubePlayerView youtubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
private static final int RECOVERY_DIALOG_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubeView);
play_btn = findViewById(R.id.playvideo_btn);
final android.app.Activity myActivity = this;
onInitializedListener =new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("Up9BjrIuoXY");
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(myActivity, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), youTubeInitializationResult.toString());
Toast.makeText(myActivity, errorMessage, Toast.LENGTH_LONG).show();
}
}
};
play_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
youtubePlayerView.initialize("AIzaSyZ2", onInitializedListener);
}
});
}
}
YouTube app of the Android 11 devices is updated.
Hope somebody could help me. Thanks!