Embed Video in your Android Application Using YouTube Android Player API v1.2.1

With YouTube Android Player API, you can embed videos and playlists into your application. User gets playback and controlling experience much similar Official YouTube Android Application. User can control loading and playing of embedded YouTube video. Playing, cueing and loading can be controlled programmatically as well. Event listeners api’s with support of events like open fullscreen or player loading etc gives you complete control that you would desire of.

YouTube Android Player Api client library is dependent on YouTube Application, it interacts with services part of YouTube application for video playback.


[su_button url=”https://github.com/androidsrc/YouTubeApiIntegration” target=”blank” style=”stroked” background=”#51d461″ color=”#ffffff” size=”6″ center=”yes” radius=”0″ icon=”icon: arrow-circle-o-down”] Download Source Code[/su_button]


[su_carousel source=”media: 467,466,465″ link=”lightbox” width=”900″ height=”500″ items=”1″ title=”no” mousewheel=”no”]


Step 1. Registering application with Google Developers Console

1.1 Go to Google Developers Console, Create a new project if none exists or select an existing project.

1.2 Navigate to APIs & auth -> APIs in left sidebar, browse for YouTube Data API v3 and turn on its status accepting terms of services.




1.3 Generate SHA1 fingerprint using java keytool utility

For getting API key, we need to generate SHA-1 fingerprint using java keytool. Open your command prompt and execute the below mentioned command to generate SHA-1 fingerprint. If keytool is not recognized, you can find it in bin directory of installed jre. In my case C:\Program Files\Java\jre7\bin.

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




From output note down SHA1 output, “FD:0E:04:E9:99:28:B9:3D:E7:AC:75:AF:6E:2B:F6:E7:CD:EE:CA:96″ in my case.


1.4 Generate API Key

Navigate to APIs & auth -> credentials in left sidebar, select Create New Key and opt for Android key.




Enter your SHA1 fingerprint and application package name sperated by semi-colon(;) and select create. It will generate API key for your application. Note down API key for later usage. API Key generated in my case is AIzaSyBcTwxVG7eYC314bzw1D28XwFi5xe6DT7k.



Step 2. Developing Sample Application using YouTube Android Player API

2.1 Create new Android Application Project in Eclipse with package name.




2.2 Download latest version 1.2.1 of YouTube Android Player API and extract downloaded file.

2.3 From extracted files, copy YouTubeAndroidPlayerApi.jar from libs folder to add it to libs folder of your android application.

2.4 Preparing Application Manifest File

Add android.permission.INTERNET permission to access Internet. We will have just one activity in our application which will embed YouTube video.

<?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" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

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

2.5 Preparing Layout File

In layout file, add com.google.android.youtube.player.YouTubePlayerView view which will used for video playback. Modify your launcher activity layout as below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"




2.6 Preparing Launcher Activity

For embedding YouTube video in an activity. We must take care of two points.
1. In order to incorporate YouTubePlayerView views in your UI, you must extend YouTubeBaseActivity.
2. Implement YouTubePlayer.OnInitializedListener for listening to intialization callback of success or failure. We set this callback while intializing YouTubePlayerView.

In case of successful intialization of YouTubePlayerView, we get object of YouTubePlayer which can be used to control player programmatically to cue videos and control playback etc. For failure case, we check if it is recoverable error then we reinitialize YouTubePlayerView.

For listening to fullscreen change events, we can use YouTubePlayer.OnFullscreenListener

	private class FullScreenListener implements YouTubePlayer.OnFullscreenListener{

		public void onFullscreen(boolean isFullscreen) {
			//Called when fullscreen mode changes.



For listening to playback events like buffering, play, pause, seek and stop, you can use YouTubePlayer.PlaybackEventListener.

	private class PlaybackListener implements YouTubePlayer.PlaybackEventListener{

		public void onBuffering(boolean isBuffering) {
			// Called when buffering starts or ends.


		public void onPaused() {
			// Called when playback is paused, either due to pause() or user action.


		public void onPlaying() {
			// Called when playback starts, either due to play() or user action.


		public void onSeekTo(int newPositionMillis) {
			// Called when a jump in playback position occurs,
			//either due to the user scrubbing or a seek method being called


		public void onStopped() {
			// Called when playback stops for a reason other than being paused.



For listening to player state change events, implement YouTubePlayer.PlayerStateChangeListener

	private class PlayerStateListener implements YouTubePlayer.PlayerStateChangeListener{

		public void onAdStarted() {
			// Called when playback of an advertisement starts.


		public void onError(ErrorReason reason) {
			// Called when an error occurs.


		public void onLoaded(String arg0) {
			// Called when a video has finished loading.


		public void onLoading() {
			// Called when the player begins loading a video and is not ready to accept commands affecting playback 


		public void onVideoEnded() {
			// Called when the video reaches its end.


		public void onVideoStarted() {
			// Called when playback of the video starts.



Our main activity code will be as below. For cueing videos in YouTubeVideoPlayer, we need to provide video id for it. I have taked video id for song “Let It Go” from Frozen movie. On intialization of view, we will cue this video. For keeping it simple, i have just used initialization listener.

package com.androidsrc.youtubeapidemo;

import android.content.Intent;
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.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class PlayVideoActivity extends YouTubeBaseActivity implements
		YouTubePlayer.OnInitializedListener {

	private static final int RECOVERY_DIALOG_REQUEST = 10;
	public static final String API_KEY = "AIzaSyBcTwxVG7eYC314bzw1D28XwFi5xe6DT7k";

	//From URL -> https://www.youtube.com/watch?v=kHue-HaXXzg
	// Let It Go : "Frozen"
	private String VIDEO_ID = "kHue-HaXXzg";

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
	    youTubeView.initialize(API_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("YouTube Error (%1$s)",
			Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();


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

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

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


2.7 Build and Run your Application

If you have completed all steps above carefully, build and run your application. You will see YouTube video embedded in your application.

You may also like...

9 Responses

  1. Heidi says:

    Hello Author. I have followed all your instructions. There are no errors, but when I run it on my device, it force closes. Any idea why this happens. Thanks.

  2. KocuOgebz says:

    Hi, i try your code. but when i run show message “Get YouTube App” This app won’t run without the youtube App, which is missing form your device. Any idea? thanks

  3. sam says:

    Hello i want to embed my video in app which can play offline so kindly guide me thanks!
    Ex When user will start app then video will start playing without internet. My video is not on youtube.

  4. Humayoon says:

    hy every one I have embed video link of dailymotion i want to get m3u8 link from embed link not using html parsing kindly tell me the other way

  5. adamzfun says:

    So how about if you want this to read a youtube playlist from an xml file? Can you embed live channels from youtube?

  1. March 29, 2016

    […] Embed Video in your Android Application Using YouTube Android Player API v1.2.1 […]

Leave a Reply

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