public class MainActivity extends YouTubeBaseActivity {
YouTubePlayerView youTubePlayerView;
YouTubePlayer player;
private static String API_KEY = "AIyaSyDpsLddBj2ISc-NHU4sxWFh4JlcHNELir8"; // Your API Key
private static String videoId = "Mx5GmonOiKo"; // Youtube video ID from https://youtu.be/Mx5GmonOiKo
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPlayer();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadVideo();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playVideo();
}
});
}
public void initPlayer() {
youTubePlayerView = findViewById(R.id.youTubePlayerView);
youTubePlayerView.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, boolean b) {
player = youTubePlayer;
youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
@Override
public void onLoading() {
}
@Override
public void onLoaded(String s) {
Toast.makeText(getApplicationContext(), s + " loaded", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdStarted() {
}
@Override
public void onVideoStarted() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
}
});
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
public void loadVideo() {
if (player != null) {
player.cueVideo(videoId);
// Loads the specified video's thumbnail and prepares the player to play the video, but does not download any of the video stream
// until play() is called.
}
}
public void playVideo() {
if (player != null) {
if (player.isPlaying()) {
player.pause();
} else {
player.play();
}
}
}
}