We can see lot of android apps playing videos inside the app demonstrating app overview or an intro. Storing the video inside the project will increase the app size. So instead, we can upload the video to YouTube and stream it in the app to decreases the app size.

In this tutorial we are going to learn how to play YouTube video in the app. This app will have a single screen with a video playing in it. This article covers very basics of YouTube Android API. If you want to dig deep and build a fully fledged youtube app, please go through YouTube Android Player API docs provided by Google.

Android playing youtube video

As we are interacting with Google APIs, we need to get the Google Developer API Key first. Follow below steps to obtain your Google Developer Android API Key.

1. Obtaining the Android API Key

1. First we need to get the SHA-1 fingerprint on your machine using java keytool. Execute the below command in cmd/terminal to get the SHA-1 fingerprint.

On Windows

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

On Linux or Mac

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
android sha1 fingerprint

2. Go to Google Developer Console and select or create a new project.

3. On the left sidebar, select APIs under APIs & auth and turn the status ON for YouTube Data API v3.

4. On the left sidebar, select Credentials and Create new key under Public API acess.

5. When popup comes asking you to choose platform, select Android Key.

6. Paste the SHA-1 key and your project’s package name separated by semicolon(;).

7. Click on create. Now you should see the API KEY on the dashboard.

android google developer console api key

Now we have the API Key required for this project. Let’s create a new android project and start building the app.

2. Creating the Android Project

1.In Eclipse create a new android project by navigating to File ⇒ New ⇒ Android Application Project and fill out all the required details.

2. Download the latest of version of YouTube Android Player API and extract it. Once extracted, you can find YouTubeAndroidPlayerApi.jar file inside libs folder.

3. Paste the YouTubeAndroidPlayerApi.jar file in your project’s libs folder.

4. Add the below string values to strings.xml located under res ⇒ values.

<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">Youtube Player</string>
    <string name="title_logo">NATIONAL GEOGRAPHIC</string>
    <string name="btn_skip_intro">Skip Intro</string>
    <string name="error_player">There was an error initializing the YouTubePlayer (%1$s)</string>


5. Also add these color values to colors.xml located under res ⇒ values. If you don’t see colors.xml, create a new file with the same name.

<?xml version="1.0" encoding="utf-8"?>
    <color name="shadow">#555555</color>
    <color name="title">#777777</color>

6. Create a class named Config.java to keep our app configuration variables like Google Developer Key and YouTube video id.

In the below class, you need to replace the DEVELOPER_KEY with your own API KEY that we generated in the Google Developer Console.
package info.androidhive.youtubeplayer;

public class Config {
	// Google Console APIs developer key
	// Replace this key with your's
	public static final String DEVELOPER_KEY = "AIzaSyABYoczeHg4XABx_jMRfv-CqmA2YMsIY4A";
	// YouTube video id
	public static final String YOUTUBE_VIDEO_CODE = "_oEA18Y8gM0";

7. Download this drawable folder and paste it in your project’s res folder. This folder contains few images required for this project.

8. Create an xml file named rouned_corner_shadow.xml inside drawable folder. This drawable layout gives rounded corner background with a shadow effect to the view.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

        <shape android:shape="rectangle" >
            <solid android:color="@color/shadow" />

            <corners android:radius="4dp" />
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/white" />

            <corners android:radius="4dp" />


9. Now open the layout file of your main activity (activity_main.xml) and add below code. This creates a simple layout with YouTubePlayerView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" >

        android:src="@drawable/snake_bg" />

        android:orientation="vertical" >

            android:orientation="vertical" >

                android:layout_marginBottom="30dp" />

                android:src="@drawable/nat_geo_logo" />

                android:textStyle="bold" />

                android:src="@drawable/wild" />

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


10.Open your main activity class (MainActivity.java) and do the below simple changes. Here the activity is extended from YouTubeBaseActivity which will be present in YouTubeAndroidPlayerApi.jar. This activity also contains few initialization listener methods to know the status of the youtube player.

package info.androidhive.youtubeplayer;

import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
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.PlayerStyle;
import com.google.android.youtube.player.YouTubePlayerView;

public class MainActivity extends YouTubeBaseActivity implements
		YouTubePlayer.OnInitializedListener {

	private static final int RECOVERY_DIALOG_REQUEST = 1;

	// YouTube player view
	private YouTubePlayerView youTubeView;

	protected void onCreate(Bundle savedInstanceState) {


		youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);

		// Initializing video player with developer key
		youTubeView.initialize(Config.DEVELOPER_KEY, this);


	public void onInitializationFailure(YouTubePlayer.Provider provider,
			YouTubeInitializationResult errorReason) {
		if (errorReason.isUserRecoverableError()) {
			errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
		} else {
			String errorMessage = String.format(
					getString(R.string.error_player), errorReason.toString());
			Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();

	public void onInitializationSuccess(YouTubePlayer.Provider provider,
			YouTubePlayer player, boolean wasRestored) {
		if (!wasRestored) {

			// loadVideo() will auto play video
			// Use cueVideo() method, if you don't want to play it automatically

			// Hiding player controls

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

	private YouTubePlayer.Provider getYouTubePlayerProvider() {
		return (YouTubePlayerView) findViewById(R.id.youtube_view);


11. Finally open your AndroidManifest.xml and add INTERNET permission.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

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

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

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


Now if you run the project, you should see the youtube video playing on launching of the app. Below is the final output of this tutorial.

android playing youtube video
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Kishan Patel

    There was a problem with the network 400 Error how can i solve this.

    • Gowtham Nimmagadda

      @disqus_GLIqF3b0LN:disqus What is the parameter used in loadVideo method ?

    • You are using wrong video id check the Confg.YOUTUBE_VIDEO_CODE

  • Kishan Patel

    hello sir,
    how to get youtube channel video play in app

  • Jagadeesh Sandireddy

    you have not mentioned about gradle

  • kantamanitagargunti

    how to implement you tube videos in recycler view?

  • Android Developer

    NullPointerException: at youTubeView.initialize(Config.DEVELOPER_KEY, this);
    Please Help!!

    • Anup Sarkar

      At first get your API key from developer console and use it.

  • test

    if I want to show toast on video end what should I do???

  • Dnyaneshwar

    When i run the app then it shows “Unfortunatley, Youtube Player has Stopped” and there is no error or warning in Android Studio -> Run… can you tell me what is the issue..?

  • Don Zarrillo Jr.

    What’s the best way to handle screen orientation change?

  • Abhishek Parashar

    how to add thumbnail?

  • Joseph Chandrasekar

    Kudos 🙂

  • Keshav Katad

    is it possible user can upload video to you tube channel through android application

  • Anup Sarkar

    Nice tutorial…working smoothly.

  • Dalayya Kalla

    Nice tutorial. I want to know one thing i.e., is this unlimted for play youtube videos. Iam trying to add in one production app.There are many downloads for that app so?.

  • Nithin

    is there any way to integrate youtube without using youtube base activity? facing a new issue while using youtube base activity that extends Activity not ActivityComact

    • Check the official docs once. There might be new library available.

  • saitejaswini kothireddy

    can you write a code for subscribing a youtube channel when a button is clicked and when we subscribe we have to get a popup

  • Naseem Ali

    So I Cannot Use This Inside A Fragment?

  • Alok Saxena

    java.lang.IllegalArgumentException: callingAppVersion cannot be null or empty

  • ali

    how to add transcript

  • Nick Theinvincibleprints

    How to loop the video?

    • Currently there is no method. You can add a listener to player and once the video ended, you can play it again.

  • Fatima Rashid

    Hi Ravi, I am trying to play video in android app. I followed the steps but app crashes when launch. any reason why?

  • Kalanidhi M

    Hi, How can we pass search content to you tube api

  • rohan

    sir how can i add push stop in that

  • Parvesh Monu

    Sir, it running awesome on some devices but on some devices, it showing error


    And it starts to work if youtube is running in the background,
    Please help me resolve this problem

  • Masti Fun Series

    How i am like and dislike YouTube video and Subscribe the YouTube Channel from my Android Application. it’s possible or not Sir.
    Please tell me my email lakhanalbert@gmail.com

  • Kritesh

    Hello sir that is awesome but can detect swipe Touch listener in YouTubePlayerView
    Please give me answer

  • Salman Faris

    Is there any tutorial for Uploading video from android to Youtube using API.

  • yogesh kahar

    multiple YouTube video player in one activity with different videos in android

  • @pk

    Hello sir is there any api for youtube releted video