When I tried to play YouTube videos on Android 9 and Android 10 devices, they played just fine. However, when I opened the YouTube video window on an Android 11 smartphone, I saw the following message:
"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);
}
});
}
}
The YouTube app for Android 11 devices is updated.
Hope somebody could help me. Thanks!