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:
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:
- Copy the jar file from libs folder to the the libs folder of your project.
- Right click on your project, Build Path -> Configure Build Path -> Libraries Tab
- Add Jars -> Select Your project’s libs folder -> Select YouTubeAndroidPlayerAPI.jar ->Ok
- 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:
- Login to API console
- Create a Project -> Goto Services -> Turn on the switch for Google YouTube Data API v3
- Goto API Access -> Create new Android Key-> In popup enter one SHA1 certificate fingerprint and package name (separated by a semicolon) per line.
- To get SH1 certificate of your app open command prompt, navigate to your Java bin folder and enter this command:
keytool.exe -V -list -alias androiddebugkey -keystore "C:\Users\Truiton\.android\debug.keystore" -storepass android -keypass android
- In the above command just replace the keystore user path with your system’s user path, and this should work.
- From here copy Sh1 certificate and also copy package name of your spp from eclipse.
- 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="http://schemas.android.com/apk/res/android" package="com.truiton.youtubeapi" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.truiton.youtubeapi.TruitonYouTubeAPIActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Lets define the layout which we are going to use for Android YouTube API:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".TruitonYouTubeAPIActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout>
Have a look at the above layout, here the com.google.android.youtube.player.YouTubePlayerView
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 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.YouTubePlayerView; import com.google.android.youtube.player.YouTubePlayer.Provider; 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_you_tube_api); YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); youTubeView.initialize(YoutubeDeveloperKey, this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.you_tube_api, menu); return true; } @Override 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", errorReason.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } } @Override 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(R.id.youtube_view); } @Override 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) { YPlayer.cueVideo("2zNSgSzhBfM"); } } }
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.
Born in New Delhi, India. A software engineer by profession, an android enthusiast and an evangelist. My motive here is to create a group of skilled developers, who can develop something new and good. Reason being programming is my passion, and also it feels good to make a device do something you want. In a very short span of time professionally I have worked with many tech firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, and whenever I get spare time I share my thoughts here at Truiton.
It worked wonderful, but when i click on Full_Screen sometimes Youtube either gets crashed or keep on reloading/flashing screen for several minutes.
i use same code,getting an error emulator unfortunate close.
it will work on emulator or not
it will work on your device on which youtube is intalled
Hello thank-you for such nice tutorial
One question will i be able to run multiple videos with this same code??
Code is fine and perfect.I am searching for Youtube Api tutorials with “extends fragment”.Can you please provide it
Well I forgot to add permission for Internet in Manifest file.. 🙂
Thanks.. Its working like charm..
I can’t make it with android studio it says ” an error occured while initializing the youtube player”
pls help me.
not play video in the genymotion
but i run it my phone, it play video good
Thanks Mohit Gupt
hai mohit i want to upload a video from my Android app to youtube for that can you please help me by your tutorial.
there is any way to get like/dislike actions??
What is mean code “2zNSgSzhBfM”?
This is the YouTube videoId.
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
Hi,
I am new to YouTube API and I am bit confused where to place the TruitonYouTubeAPIActivity.java file at?
also will this tutorial works for a YouTube channel? or is this only for one video?
Thank you
It works perfect for me. But if it’s possible to customize player UI?
thanks a lot . I was searching for hours and found this link. It was very helpful.
Thank you, very helpful!
Do you have any idea how to set the streaming quality?
what is R.menu.you_tube_api? it is showing error
Its required to inflate menu xml. You can comment out
onCreateOptionsMenu
method.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.
Thanks.
Hello sir,
Will this work for youtube live streaming videos?
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.
When i try to embed url from any channel like
“v=ZYuk9ogmms0&list=PLonJJ3BVjZW7LFiBUpg5jo7CmzfVktV-o”
I am getting “There was a problem with the network [400] error.
Please help me solving this.
Hi Sujit,
Did you solve the problem? I got the same issue and wondering how to fix it.
Hi Josef, Sujit,
For playing channels please refer to this tutorial
https://www.truiton.com/2015/03/android-youtube-api-example-channels/
-Mohit
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 ?
Thanks,
Thank your for this great work.
How do I play my own Videos other from youtube ones eg http://**********/****.mp4 ?
Please see the list of supported video formats in android:
http://developer.android.com/guide/appendix/media-formats.html
Nice tutorial
it would be great if you will also post how to fetch youtube channel playlist in app
thanks:)
how to use dynamic VIDEO_ID of youtube after clicking on ListView ?
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.
Hi there. Are there some ways to play local video on youtube player? Please, I need some solution for it.
can you make a tutorial using youtube api and playing different videos base on what the choice the user made in the listview