我尝试了这个YouTube视频中解释的如何在Android应用程序中播放YouTube视频的项目:
https://www.youtube.com/watch?v=Up9BjrIuoXY
我尝试使用运行Android 9和Android 10的设备播放YouTube视频,它们都能正常播放,但是在Android 11设备上,我在YouTube视频窗口内收到了以下消息:
"An error occurred while initializing the YouTube player"
这是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);
}
});
}
}
安卓 11 设备的 YouTube 应用程序已更新。
希望有人能帮帮我。谢谢!