Youtube Integration in Android

  1. Go to the Google Developers Console
  2. Create a new project. My Project Name is YouTubeExample.
  3. In the sidebar on the left, make sure that Library is selected. On the right panel, select the Youtube Data API V3 and Enable it on the page that follows.
  4. In the sidebar on the left, select Credentials. For credentials, the API supports OAuth 2.0, the use of an API key and of a Service account. We’ll use the API key option.
  5. Select API key from the Create Credentials drop-down menu. A popup will appear with the value of your API key. Keep this window open, we’ll use the key in the next step.
Example

Creating the Android Project in Android Studio.

1. Top-Left Side File >> New >> New Project.

2. Download YouTube Android Player APIand extract the zip file.

3.  Once extracted, you can find YouTubeAndroidPlayerApi.jar file inside libs folder.

4.  YouTubeAndroidPlayerApi.jar file copy and Paste in Android Project.(Selected : Project >> YouTubeExample (Your_App)>> app >>libs (paste here)).

5. Add the permission for internet access to the AndroidManifest.XML file as a child of the tag manifest and a sibling to theapplication tag

<uses-permission android:name="android.permission.INTERNET"/>

6.Modifyactivity_main.xml as shown.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              tools:context=".MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/seek_to_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:background="@android:drawable/editbox_background"
            android:hint="20"
            android:inputType="number" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:text="in Second" />

        <Button
            android:id="@+id/seek_to_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:text="Jump" />

    </LinearLayout>
</LinearLayout> 

7. Modify MainActivity.java as shown.

public class Main2Activity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener{


// YOUR DEVELOPER KEY (google_developer_key)
public static final String DEVELOPER_KEY = "AIzaSyCfZOoU36fSEp2wOSjvz3fwy_fxrTosEKo";

//YOUTUBE VIDEO CODE
// (Copy From YouTube URL in last like: https://www.youtube.com/watch?v=xDMP3i36naA)
public static final String YOUTUBE_VIDEO_CODE1 = "xDMP3i36naA";
public static final String YOUTUBE_VIDEO_CODE2 = "iNJdPyoqt8U";
public static final String YOUTUBE_VIDEO_CODE3 = "Bey4XXJAqS8";

private static final int RECOVERY_REQUEST = 1;

//Event Listener Class
private VideoPlaybackEventListener videoPlaybackEventListener;
//Status Change Class
private VideoPlayerStateChangeListener videoPlayerStateChangeListener;

private VideoPlayerOnFullscreenListener videoPlayerOnFullscreenListener;

private VideoPlayerPlaylistEventListener videoPlayerPlaylistEventListener;
private YouTubePlayer player;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);

final EditText seekToText = (EditText) findViewById(R.id.seek_to_text);
Button seekToButton = (Button) findViewById(R.id.seek_to_button);

seekToButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (player!=null) {
int skipToSecs = Integer.valueOf((seekToText.getText().toString().equalsIgnoreCase("")?"0":seekToText.getText().toString()));
player.seekToMillis(skipToSecs * 1000);
}else {
Toast.makeText(Main2Activity.this,"Error Message", Toast.LENGTH_LONG).show();
}
}
});

videoPlaybackEventListener=new VideoPlaybackEventListener();
videoPlayerStateChangeListener= new VideoPlayerStateChangeListener();
videoPlayerOnFullscreenListener=new VideoPlayerOnFullscreenListener();
videoPlayerPlaylistEventListener=new VideoPlayerPlaylistEventListener();
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
    
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
    
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
    
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
if (!wasRestored) {

// Use cueVideo() method, if you don't want to play it automatically
player.cueVideo(YOUTUBE_VIDEO_CODE1);

//Video List
ArrayList arrayList = new ArrayList();
arrayList.add((Object)(YOUTUBE_VIDEO_CODE1));
arrayList.add((Object)(YOUTUBE_VIDEO_CODE2));
arrayList.add((Object)(YOUTUBE_VIDEO_CODE3));
player.loadVideos((List)(arrayList));



// only for single Video
// player.loadVideo(YOUTUBE_VIDEO_CODE);


// Hiding player controls
//player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
    
//show player controls (option)
//player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
    
//DEFAULT player controls (option)
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);

//player Listeners
player.setPlaybackEventListener(videoPlaybackEventListener);
player.setPlayerStateChangeListener(videoPlayerStateChangeListener);
player.setOnFullscreenListener(videoPlayerOnFullscreenListener);
player.setPlaylistEventListener(videoPlayerPlaylistEventListener);
}
}


public void showMessage(String message) {

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}



public class VideoPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {

View view;
@Override
public void onPlaying() {
showMessage("Playing");
}

@Override
public void onPaused() {
showMessage("Paused");
}


@Override
public void onStopped() {
showMessage("Stopped");
}

@Override
public void onBuffering(boolean b) {
showMessage("Buffer :"+b);
}

@Override
public void onSeekTo(int i) {
showMessage("Seek :"+i);
}

}

public class VideoPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
@Override
public void onLoading() {
showMessage("Loading");
}

@Override
public void onLoaded(String s) {
showMessage("Loaded");
}

@Override
public void onAdStarted() {
showMessage("AdStarted");
}

@Override
public void onVideoStarted() {
showMessage("VideoStarted");
}

@Override
public void onVideoEnded() {
showMessage("VideoEnded");
}

@Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
showMessage("onError"+errorReason);
}
}

public class VideoPlayerOnFullscreenListener implements YouTubePlayer.OnFullscreenListener{

@Override
public void onFullscreen(boolean b) {
showMessage("FullScreen :"+b);
}
}

public class VideoPlayerPlaylistEventListener implements YouTubePlayer.PlaylistEventListener{

@Override
public void onPrevious() {
showMessage("Previous video");
}

@Override
public void onNext() {
showMessage("Next video");
}

@Override
public void onPlaylistEnded() {
showMessage("Play List End");

}
}
} 

In the above code, we created or Modify MainActivity.java file,

Class MainActivity is Subclass of YouTubeBaseActivity, This is required to

make use of YouTubePlayerView and implemented YouTubePlayer.OnInitializedListenero listens for initialization success or failure.

This Interface has two Method onInitializationSuccess and onInitializationFailure.

onInitializationSuccess this method called when Video Success and on initialization failure

this method called when Video not Loaded, getting Some Error or fail.

Playback Events and State Changes Listener, In the app some Time We need to

Take the same action or get information about Video action Like Video Playing, Paused, Stopped,

Buffering, Seek.

  The YouTubePlayer has the following interface.

  • YouTubePlayer.PlayerStateChangeListener
  • YouTubePlayer.PlaybackEventListener
  • YouTubePlayer.OnFullscreenListener
  • YouTubePlayer.PlaylistEventListener