我尝试了这个 YouTube 视频中解释的如何在 Android 应用上播放 YouTube 视频的项目:
https://www.youtube.com/watch?v=Up9BjrIuoXY
我尝试在使用 Android 9 和 Android 10 的设备上播放 YouTube 视频,并且视频可以正确播放,但在 Android 11 设备中,我在 YouTube 视频窗口中收到了以下消息:
“初始化 YouTube 播放器时出错”。
这是 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);
}
});
}
}
Android 11 设备的 YouTube 应用程序已更新。
希望有人可以帮助我。谢谢!