Jack and Jill says this tutorial is retired. And we agree! This tutorial was published back in May 2014, since then lot has been changed; YouTubePlayerAPI is updated and Eclipse for Android development is history. Checkout our new YouTube Android Player API Example here.

In this tutorial we’ll see how to use YouTube Player API in android. YouTube player API provides an embedded view that supports with various playback controls.

1. Downloading YouTube Player API

Before you start writing some code, you’ll have to first download the YouTube Android Player API. Once downloaded import the jar into your project lib folder and add the jar to your build path.

Download YouTube Player API here

YouTube Android Player API

2. Register your app in Google developer console

  • Before you start using the Youtube player API for android, you have to register your application with Google developer console and get and API key, The API key is a unique value for your application. Do not disclose this to others.
  • Visit Google APIs Console and login with your Google account and create a new project
  • Once your project is created, got to API’s and enable YouTube data API V3
  • And then Select API Access in your API Console. You’ll find API key. This API key will be used to access YouTube Android Player APIs.

YouTube Android Player API2

3. Create a new Android Application project

Now you are ready to create Android project to play YouTube videos using YouTube player API. You may use IDE of your choice, here I am using Eclipse.

You need INTERNET permission to play video over internet. Add below permission in your application AndroidManifest.xml file.

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

4. Define your activity layout

In this example, we will create an simple layout that uses YouTubePlayerView inside an LinearLayout.

<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" >

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:padding="5dp" />

</LinearLayout>

5. Initialize YouTubePlayerView in your Activity

Initializing YouTube player view by calling initialize methood. Once the initialize is successful, you will get the onInitializationSuccess() callback with YouTubePlayer instance. You can add additional listeners to handle the playback control events.

package com.javatechig.youtubeapp;

import android.os.Bundle;
import android.widget.Toast;
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.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import com.javatechig.youtubeandroid.R;

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
	public static final String API_KEY = "YOUR API KEY";

	//http://youtu.be/<VIDEO_ID>
	public static final String VIDEO_ID = "dKLftgvYsVU";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/** attaching layout xml **/
		setContentView(R.layout.activity_main);

		/** Initializing YouTube player view **/
		YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
		youTubePlayerView.initialize(API_KEY, this);
	}

	@Override
	public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
		Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
		/** add listeners to YouTubePlayer instance **/
		player.setPlayerStateChangeListener(playerStateChangeListener);
		player.setPlaybackEventListener(playbackEventListener);

		/** Start buffering **/
		if (!wasRestored) {
			player.cueVideo(VIDEO_ID);
		}
	}

	private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {

		@Override
		public void onBuffering(boolean arg0) {
		}

		@Override
		public void onPaused() {
		}

		@Override
		public void onPlaying() {
		}

		@Override
		public void onSeekTo(int arg0) {
		}

		@Override
		public void onStopped() {
		}

	};

	private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {

		@Override
		public void onAdStarted() {
		}

		@Override
		public void onError(ErrorReason arg0) {
		}

		@Override
		public void onLoaded(String arg0) {
		}

		@Override
		public void onLoading() {
		}

		@Override
		public void onVideoEnded() {
		}

		@Override
		public void onVideoStarted() {
		}
	};
}

6. Output
YouTube Android Player API Example - Javatechig

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.
  • Jeevan Prasad

    https://uploads.disquscdn.com/images/d0edbcbd618b9ae7bdb15b5208507e9d4201f454c3e623ec1b4f100969ea94f1.png

    Hi,
    I am using again and download Youtubeplayerapi.zip.1.2.2 pest in lib folder after synck but not able to extend youtubebaseactivity .Please help me.So please see my attachment.

  • Unfortunately no. The Android Player API doesn’t have any methods to determine the video playback quality. The video quality is automatically managed by library based on network bandwidth and screen size. However there is no official mention about playback quality.

  • Paul Hyman

    Get example. But do you have any example for YouTubePlayerFragement?

  • Aleksandar Noveski

    How can I play 3 videos like this in one xml layout?

  • Nikola Brodar

    hey guys.. can you please help me.. I would to start playing youtube video, after 2,3 seconds. After youtube makes just a little buffering, I would like to start it playing. Sometimes youtube video plays after 2,3 seconds, sometimes not. I have tried with this example also, but it does not always play after 2,3 seconds.

    Especially on android 6.0, or android API 23. There it start to play video after 8, 10, 12, 13 seconds. But sometimes it start to play after 2, 3 seconds. Why is this so?

  • Nikola Brodar

    hey guys.. can you please help me.. I would to start playing youtube video, after 2,3 seconds. After youtube makes just a little buffering, I would like to start it playing. Sometimes youtube video plays after 2,3 seconds, sometimes not. I have tried with this example also, but it does not always play after 2,3 seconds.
    Especially on android 6.0, or android API 23. There it start to play video after 8, 10, 12, 13 seconds. But sometimes it start to play after 2, 3 seconds. Why is this so?

  • Nikola Brodar

    question guys.. how long does your youtube video loads?
    For me, for example it takes 4,5,6 second.. and the download speed is 500 KB..
    I want to create a youtube, that starts to play after 2,3 second, after buffers just a little data, and start to play. If youtube player buffers just a little data, I want it to play.. Can you please, help me to achieve this?
    Thank you a lot :D

  • Nikola Brodar

    create a listview with pictures. If user click on picture, then it will load, play video for this second picture. This picture is also your thumbail. We can say it that way.

  • Huy Nguyễn Quốc

    so you should to remove line ‘ android:padding=”5dp” ‘ in activity_main.xml .

  • pawandeep Kaur

    hey i want to get core metrics data from youtube please help me

  • yann harold

    hello ! i want to list all channel’s videos in my android app. please help me.

  • Android Example
  • Harsha Bhagwat

    Thanks a lot..How do I play video automatically in a stretched view(auto rotated) once I load the activity or on pressing some button??that is it should directly play as shown in the second screenshot of your output.many thanks for any suggestions.

  • Dhiraj Devkar

    I followed your tutorial but now I got the the error as
    an error occured while initialising the you tube player

  • Arun Badole

    Hi, a very nice tutorial. Can I capture frame (in jpeg or png format) from YouTubePlayerView?

    • Nilanchala Panigrahy

      Not quite sure, but as per my knowledge you can’t capture the running frame

  • Nilanchala Panigrahy

    Android key

  • Nilanchala Panigrahy

    do you mean multiplayer. both side by side?

    • Krushit Patel

      yes i do
      but now it has been completed

  • Pushkaraj

    Hey,

    I have a youTubePlayer and some 2-3 different thumbnails. When I play any video it plays for one second and stops. It keeps on happening when I play the video again. But if the video is playing in fullscreen mode, it plays without pausing. The internet connectivity is good.

    As part of activity XML, I have created a linear layout which has youTubePlayer . And below that I have added 2 thumbnails with different VIDEO_IDs. When I press on thumbnail, proper video is being played, that is not the issue. The only issue is why is the video stopping (Pausing to be precise) after a second of playback.

    Any inputs will really be appreciated.

    • Are you performing any long running or blocking task?

    • Seb

      Same problem for me: the video pauses one second after playing. Any help?

  • Ashish Bhagat

    Can we disable seekbar control of this you tube player in android?

    • Yes, you can do that using YouTubePlayer.PlayerStyle class.

      setPlayerStyle(YouTubePlayer.PlayerStyle style)

      player style can be of any of the following

      1. YouTubePlayer.PlayerStyle.CHROMELESS- A style that shows no interactive player controls.

      2. YouTubePlayer.PlayerStyle.DEFAULT- The default style, showing all interactive controls.

      3. YouTubePlayer.PlayerStyle.MINIMAL A minimal style, showing only a time bar and play/pause controls.

      • Ashish Bhagat

        thank you very much…

        • :-)

          • john

            Can we hide or remove youtube logo in player for android

          • I don’t think so you can do that.. However, I have not explored the new API.

  • Take a look at youtube JSON API developer guide

    https://developers.google.com/youtube/2.0/developers_guide_json

  • Evans Kakpovi

    how do you add support for age-restricted videos?

  • Oh, I see. By the way the code was not tested on Lollypop. Will take this and review for any changes if required.

    • Sebbe

      Does this still not work with Lollopop? and how come it doesnt work with it?

  • Yes! you can.

  • dreamgs1

    Hi,

    I have a fragmnet called FragmnetVideo which is one of 4 fragmnets managed by FragmnetStatePageAdaper.

    This FragmetVideo is called with a youtube video link which should be played once your scrolls to that fragment and clicks on play.

    How can I do the same in a fragmnet.

    I have already tried youtubeplayerfragment but i am not able to get it worked. I am new to android development

    below is the same query posted:

    http://stackoverflow.com/questions/26108197/youtubeplayerfragmnet-unable-to-create-a-fragment-to-play-youtube-video

    Could you please give some pointers

  • Wejdan

    thank you, it’s a very helpful tutorial!
    i tried that but i got “Failured to Initialize!” =( can you tell me why?

    • Checkout your API key. that can be a culprit.

  • Sanid Kankaeng

    can i use more than a YouTubePlayerView in once activity

  • Ngọc

    I tried to to like that but i got many bugs. How do I fix it? I run on Genymotion

    This is XML file http://ideone.com/RbXit1

    and then MainActivity http://ideone.com/bHlPM6

    • i m bond

      add youtube library in lib folder too and after that run it again

  • which device you testing on?

  • It’s possible to show us how get a youtube playlist?