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.
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
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.
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"?> <resources> <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> </resources>
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"?> <resources> <color name="shadow">#555555</color> <color name="title">#777777</color> </resources>
6. Create a class named Config.java to keep our app configuration variables like Google Developer Key and YouTube video id.
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" > <item> <shape android:shape="rectangle" > <solid android:color="@color/shadow" /> <corners android:radius="4dp" /> </shape> </item> <item android:bottom="2dp" android:left="0dp" android:right="0dp" android:top="0dp"> <shape android:shape="rectangle" > <solid android:color="@android:color/white" /> <corners android:radius="4dp" /> </shape> </item> </layer-list>
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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true" android:scaleType="centerCrop" android:src="@drawable/snake_bg" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/rouned_corner_shadow" android:gravity="center_horizontal" android:orientation="vertical" > <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="30dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="70dp" android:layout_marginBottom="20dp" android:scaleType="fitCenter" android:src="@drawable/nat_geo_logo" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="@string/title_logo" android:textColor="@color/title" android:textSize="20dp" android:textStyle="bold" /> <ImageView android:layout_width="wrap_content" android:layout_height="40dp" android:layout_marginBottom="30dp" android:scaleType="fitCenter" android:src="@drawable/wild" /> </LinearLayout> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:background="@drawable/rouned_corner_shadow" android:text="@string/btn_skip_intro" /> </LinearLayout> </RelativeLayout>
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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); // Initializing video player with developer key youTubeView.initialize(Config.DEVELOPER_KEY, this); } @Override 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(); } } @Override 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 player.loadVideo(Config.YOUTUBE_VIDEO_CODE); // Hiding player controls player.setPlayerStyle(PlayerStyle.CHROMELESS); } } @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(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" package="info.androidhive.youtubeplayer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21" /> <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=".MainActivity" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
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.
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
There was a problem with the network 400 Error how can i solve this.
@disqus_GLIqF3b0LN:disqus What is the parameter used in loadVideo method ?
You are using wrong video id check the Confg.YOUTUBE_VIDEO_CODE
hello sir,
how to get youtube channel video play in app
you have not mentioned about gradle
how to implement you tube videos in recycler view?
NullPointerException: at youTubeView.initialize(Config.DEVELOPER_KEY, this);
Please Help!!
At first get your API key from developer console and use it.
if I want to show toast on video end what should I do???
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..?
What’s the best way to handle screen orientation change?
how to add thumbnail?
Kudos 🙂
is it possible user can upload video to you tube channel through android application
Nice tutorial…working smoothly.
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?.
I think there are certain limitation on Youtube API. Check these
https://stackoverflow.com/questions/15568405/youtube-api-limitations
https://developers.google.com/youtube/v3/determine_quota_cost
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.
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
So I Cannot Use This Inside A Fragment?
java.lang.IllegalArgumentException: callingAppVersion cannot be null or empty
how to add transcript
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.
Hi Ravi, I am trying to play video in android app. I followed the steps but app crashes when launch. any reason why?
Hi, How can we pass search content to you tube api
sir how can i add push stop in that
Sir, it running awesome on some devices but on some devices, it showing error
ERROR CONNECTING TO SERVICE
And it starts to work if youtube is running in the background,
Please help me resolve this problem
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
Hello sir that is awesome but can detect swipe Touch listener in YouTubePlayerView
Please give me answer
Is there any tutorial for Uploading video from android to Youtube using API.
multiple YouTube video player in one activity with different videos in android
Hello sir is there any api for youtube releted video
Is there a way to prevent YouTube Logo on click, without disturbing the other play controls functionality like seek bar ?