Android YouTube API Tutorial - Truiton
Skip to content

Android YouTube API Tutorial

Android YouTube API

Well well its official, on 10th May 2013 Google has finally released YouTube API for android. You might be wondering what difference does it make, earlier too we were able to play YouTube videos on Android. The difference in this API is the way we are accessing it. Earlier to play a YouTube video on an Android device in an app we had to fire an Intent. Further with this Intent the android’s YouTube player App was launched and the video was played over there. But now with this new Android YouTube API we would be able to play HD YouTube videos in our Android app, i.e. without an intent. Also we would have full control over the playback.

Earlier I wrote a tutorial to play YouTube videos on android, in which the only limitation was, that we could not stream HD YouTube videos. Hence I had to write this Android YouTube API Tutorial. With this new API we can we can seamlessly stream high quality YouTube videos and also maintain their state while screen is rotated i.e. resuming video from where it stopped. Although if you would like to give a read to my tutorials on streaming YouTube video on Android please have a look at the following links:

  1. Android VideoView Example
  2. Android YouTube Player API Tutorial

To start off with Android YouTube Player API there are certain steps that are needed to be performed. But first let me introduce you to the concept through which this player works. Android YouTube Player can be used in any app by importing a library in to that app’s project, but by doing this it does not mean that you have every thing. Android YouTube Player API works along with the device’s native YouTube Player. Means even after importing a library we would require an android device which has YouTube app installed (min ver 4.2.16). In reality this API library which we imported in to our app project, will communicate with a service of Android YouTube app which is bundled with the OS. To begin the tutorial lets follow these steps:

Step 1 : Include a jar file in your project

Download Android YouTube Player API bundle from here. Unzip this file and follow the steps below to include it in your app:

  1. Copy the jar file from libs folder to the the libs folder of your project.
  2. Right click on your project, Build Path -> Configure Build Path -> Libraries Tab
  3. Add Jars -> Select Your project’s libs folder -> Select YouTubeAndroidPlayerAPI.jar ->Ok
  4. Order and Export Tab -> Check YouTubeAndroidPlayerAPI.jar – Ok

Step 2 : Create an API Key for Android YouTube Player

To access the Android YouTube Player API on device we need to create an API key from Google API developer console. The steps to do so are:

  1. Login to API console
  2. Create a Project -> Goto Services -> Turn on the switch for Google YouTube Data API v3
  3. Goto API Access -> Create new Android Key-> In popup enter one SHA1 certificate fingerprint and package name (separated by a semicolon) per line.
  4. To get SH1 certificate of your app open command prompt, navigate to your Java bin folder and enter this command:
  5. keytool.exe -V -list -alias androiddebugkey -keystore "C:\Users\Truiton\.android\debug.keystore" -storepass android -keypass android
  6. In the above command just replace the keystore user path with your system’s user path, and this should work.
  7. From here copy Sh1 certificate and also copy package name of your spp from eclipse.
  8. Now enter these values in the API Console popup in the desired format, you key will be generated.

Step 3 : Write code for Android YouTube Player API

Now that we have all the prerequisites in place lets start with the app manifest first:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="17" />

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

        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Lets define the layout which we are going to use for Android YouTube API:

<RelativeLayout xmlns:android=""
    tools:context=".TruitonYouTubeAPIActivity" >

        android:text="@string/hello_world" />

        android:layout_height="wrap_content" />


Have a look at the above layout, here the is being used to display the YouTube Video. Next lets have a look at the code through which Android YouTube Player API can be used:

package com.truiton.youtubeapi;


import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;

public class TruitonYouTubeAPIActivity extends YouTubeBaseActivity implements
		YouTubePlayer.OnInitializedListener {

	private YouTubePlayer YPlayer;
	private static final String YoutubeDeveloperKey = "AIzaSyDhEeq_FYAdCzMMSigmMcRwF_nQEhUXS-0";
	private static final int RECOVERY_DIALOG_REQUEST = 1;

	protected void onCreate(Bundle savedInstanceState) {

		YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(;
		youTubeView.initialize(YoutubeDeveloperKey, this);

	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(, menu);
		return true;

	public void onInitializationFailure(YouTubePlayer.Provider provider,
			YouTubeInitializationResult errorReason) {
		if (errorReason.isUserRecoverableError()) {
			errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
		} else {
			String errorMessage = String.format(
					"There was an error initializing the YouTubePlayer",
			Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RECOVERY_DIALOG_REQUEST) {
			// Retry initialization if user performed a recovery action
			getYouTubePlayerProvider().initialize(YoutubeDeveloperKey, this);

	protected YouTubePlayer.Provider getYouTubePlayerProvider() {
		return (YouTubePlayerView) findViewById(;

	public void onInitializationSuccess(Provider provider,
			YouTubePlayer player, boolean wasRestored) {
		YPlayer = player;
		 * Now that this variable YPlayer is global you can access it
		 * throughout the activity, and perform all the player actions like
		 * play, pause and seeking to a position by code.
		if (!wasRestored) {


To make the above Android YouTube API example work you need to specify your developer key. In above example first onCreate method is called, in this method YouTubePlayerView is initialized by YouTubePlayerView.initialize() method. Further if the initialization is successful, onInitializationSuccess() method is called. In this method one can specify the video that needs to be played. Also if you notice I have declared the player variable as a global variable by the name of YPlayer. With the help of this variable we would be able to access the Android YouTube Player API throughout the Activity, and perform play, pause, seek and various other functions.

After performing all the above steps, your app would look something like the screenshots above. An interesting feature of using this Android YouTube Player API, is that we don’t have to do any sort of programming to make the video run in full screen mode. Also no effort is required to stream HD YouTube videos. Another interesting feature is that while playback if the screen is rotated, the video playback starts exactly from where it stopped, ain’t that great as no amount of coding is to be done for this feature too. Hope this Android YouTube API Tutorial helped you in some way. If it did or you simply liked it, please like and share it with your friends on Google+ and Facebook.

34 thoughts on “Android YouTube API Tutorial”

  1. It worked wonderful, but when i click on Full_Screen sometimes Youtube either gets crashed or keep on reloading/flashing screen for several minutes.

  2. Sir i am trying to use youtube data api in my android app,,
    but i am not being able to. can you please publish a post helping me to access youtube data api in android app

  3. Hi,
    I am new to YouTube API and I am bit confused where to place the file at?
    also will this tutorial works for a YouTube channel? or is this only for one video?
    Thank you

  4. Hi Mohit,

    I want to add a skip button overlapping youtube player view, but it doesn’t allow any overlay views. Is there any work around for this. Any help would be appreciated.


  5. It worked wonderful, but when i click on Full_Screen sometimes Youtube either gets crashed or keep on reloading/flashing screen for several minutes.
    the same problem i have..! please your help..
    thank you.

  6. When i try to embed url from any channel like


    I am getting “There was a problem with the network [400] error.

    Please help me solving this.

  7. Hi Mohit,

    I wanted to thank you for this great tutorial my code seems to be very similar and what I am noticing is this memory leak when switching between the activity A (YouTubeBaseActivity) and another regular activity B, the leak happens at this level: youTubeView.initialize(YoutubeDeveloperKey, this);
    My questions is do you think it’s something that can be fixed or can it be related to the API it self that causing this leak ?


  8. Thank you Mohit, article is very informative . My idea is to list of few videos and allow the user to choose and play them , will the Youtube API and our code work .
    Thank you for your time and help.

Leave a Reply

Your email address will not be published. Required fields are marked *