How To Create Youtube Android App In Android Studio [Step By Step]

Do you know creating Youtube Android App is so easy as you just need to understand how to use Youtube API for that.

In this application we will share about adding Youtube functionality to your Android application. Further we will also create playlist and run on real device. Will make use of multiple Android UI components to design and step by step developing a Youtube App in Android Studio.

Topics Used For Creating Youtube App – Before following the below steps it is recommended you check out ImageView, Button,  Linear Layout & Relative Layout topics. Also go through JAVA OOPS concept once.


Steps To Create a Youtube Application In Android Studio:

Below you can download code, see final output and step by step explanation of Youtube App in Android Studio.

Download Code

Youtube Player App In Android Studio
Step 1: Firstly get the Android Studio downloaded in your system, then open it.

Step 2: Create a new project choose basic activity and name it YoutubePlayer.

Now please read this tutorial How To choose basic activity.

Step 3: Now click here to download the YouTube Android Player API.

Step 4: After downloading extract the downloaded compressed folder, open it and find a executable jar file in libs folder.

Now please read this tutorial How To Add External JAR Files In Android Studio

Step 5: Copy this library and paste in your YoutubePlayer application app -> libs

Adding Youtube Api To Application In Android Studio
Step 6: Add dependencies to build.gradle file and sync. Adding this will make our application compatible to add youtube functionality.

Add in Gradle Scripts >> build.gradle (Module: app)

 compile files('libs/YouTubeAndroidPlayerApi.jar')

Adding YouTube Dependency To Android Studio
Step 7: Create a new activity “YoutubeActivity” of gallery type and further select it as basic activity.
Adding Gallery Layout In Android Studio.pxr
Step 8: Open YoutubeActivity.java file. Here you need to change the default code.

i of Step 8) Firstly need to change YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener. This code will give error, to remove it we need to implement the code.

You can see it in below screenshot:
Adding Methods In Youtube Player In Android Studio

ii of Step 8 – Go to menu bar on the top click Code -> Generate -> Implements method and click ok. This will add a code where we can add toast message when youtube initialization is success and fail.

Now please read this tutorial for Implementing abstract method.

iii of Step 8) Nextly we gonna add listeners in the code as:

   youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener);
        youTubePlayer.setPlaybackEventListener(playbackEventListener);

iv of Step 8) You need to add Google API Key (it’s a unique key uses to take advantage of youtube functionality) and Youtube Video ID(it’s the id of video we want to play) for that follow following steps:

  1. Open this link first.
  2. You need to login first to get into this link thought your google ID.
  3. Now you need to create a project then name that project.
    Create New Project In Google Developer Console
  4. Click on credentials and further click API key. There will be a pop-up displaying API copy it for its usage in the application.
    Create Credentials In Google Developers Console
  5. For Video ID open Youtube.com and play any video you wish to. To get the video ID copy the URL after the equal to sign. Similarly you can get the PlayList ID just open required playlist in Youtube.
    Coping Youtube ID For App

Complete CODE of YoutubeActivity.java

package com.example.youtubeplayer;

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.YouTubePlayerView;

public class YoutubeActivity extends YouTubeBaseActivity
        implements YouTubePlayer.OnInitializedListener
{
    private String GOOGLE_API_KEY = "AIzaSyBZVbNSsdQZCX_yWFCHPQ_fQMcK4xf9hDk";
    private String YOUTUBE_VIDEO_ID = "EknEIzswvC0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_youtube);
        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
        youTubePlayerView.initialize(GOOGLE_API_KEY, this);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
        Toast.makeText(this, "Initialized Youtube Player successfully", Toast.LENGTH_LONG).show();
        youTubePlayer.setPlayerStateChangeListener(playerStateChangeListener);
        youTubePlayer.setPlaybackEventListener(playbackEventListener);

        if(!wasRestored) {
            youTubePlayer.cueVideo(YOUTUBE_VIDEO_ID);
        }

    }
    
    private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
        @Override
        public void onPlaying() {
            Toast.makeText(YoutubeActivity.this,"Good, video is playing ok", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onPaused() {
            Toast.makeText(YoutubeActivity.this,"Video has paused", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onStopped() {

        }

        @Override
        public void onBuffering(boolean b) {

        }

        @Override
        public void onSeekTo(int i) {

        }
    };

    YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
        @Override
        public void onLoading() {

        }

        @Override
        public void onLoaded(String s) {

        }

        @Override
        public void onAdStarted() {
            Toast.makeText(YoutubeActivity.this,"Click Ad now, make the video creator rich!", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onVideoStarted() {
            Toast.makeText(YoutubeActivity.this,"Video has started!", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onVideoEnded() {
            Toast.makeText(YoutubeActivity.this,"Thanks for watching!", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onError(YouTubePlayer.ErrorReason errorReason) {

        }
    };

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        Toast.makeText(this, "Failed to Initialize Youtube Player", Toast.LENGTH_LONG).show();
    }
}

Step 9: Open content_youtube.xml file, in this we need to extend the layout for youtube activity basically we will add a custom view that enable us to play youtube videos.

Step 10: Firstly change the relative layout to linear layout and add its orientation to vertical also remove the padding in the layout. See the code to be added.

Complete code of content_youtube.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_youtube"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.youtubeplayer.YoutubeActivity"
    tools:showIn="@layout/activity_youtube">

//custom view to enable youtube player
    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white">
    </com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>

Step 11: Add users permission for internet in AndroidManifest.xml.

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

Adding Internet Permission In Android Studio
Step 12: Open file content_main.xml, add button in it which will redirect user to youtube player.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_standalone"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.youtubeplayer.MainActivity"
    tools:showIn="@layout/activity_main"
    android:background="@android:color/holo_green_dark">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/pic"
        android:id="@+id/imageView"
        android:background="@android:color/background_dark"
        android:layout_alignParentTop="true" />

    <Button
        android:text="Next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnPlayVideo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="135dp"
        android:textStyle="bold|italic"
        android:id="@+id/next" />

    <Button
        android:id="@+id/btnPlayVideo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play_video"
        android:textStyle="bold|italic"
        android:layout_marginTop="93dp"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 13: Now open MainActivity.java class and paste the following code.
In this code we gonna add the onclickListener over button click i.e if user click on button video will run and a next button which will redirect to next activity.

package com.example.youtubeplayer;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
    private Button btnSingle;
    private  Button btnNext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        btnSingle = (Button) findViewById(R.id.btnPlayVideo);
        btnNext= (Button) findViewById(R.id.next);
        btnSingle.setOnClickListener(this);
        btnNext.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v) {
        Intent intent= null;

        switch (v.getId()){
            case R.id.btnPlayVideo:
                intent = new Intent((MainActivity.this), YoutubeActivity.class);
                break;
            case R.id.next:
                intent = new Intent((MainActivity.this) , StandaloneActivity.class);
                break;
            default:
        }

        if(intent!= null){
            startActivity(intent);
        }

    }
}

Step 14: Similarly create another basic activity and name  it StandaloneActivity to see the Youtube Playlist functionality. In this we will define a PlayList ID that you can get same as we extracted Video ID.

Step 15: Open content_standalone.xml file in this add two button and add functionality over it in java file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_standalone"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.youtubeplayer.StandaloneActivity"
    tools:showIn="@layout/activity_standalone"
    android:background="@android:color/holo_green_dark">
   
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/pic"
        android:id="@+id/imageView"
        android:background="@android:color/background_dark"
        android:layout_alignParentTop="true"
        android:contentDescription="@string/pic" />

    <Button
        android:id="@+id/btnVideo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play_video"
        android:textStyle="bold|italic"
        android:layout_marginBottom="186dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/btnPlayList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play_playlist"
        android:textStyle="bold|italic"
        android:layout_marginBottom="63dp"
        android:layout_above="@+id/btnVideo"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 16: Now open src -> package -> StandaloneActivity.java. In this we gonna add the onclickListener over button click i.e if user click on PlayVideo video will play otherwise on clicking Play PlayList playlist will run of defined ID.

package com.example.youtubeplayer;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

import com.google.android.youtube.player.YouTubeStandalonePlayer;

public class StandaloneActivity extends AppCompatActivity implements View.OnClickListener
{

    private String GOOGLE_API_KEY = "AIzaSyBZVbNSsdQZCX_yWFCHPQ_fQMcK4xf9hDk";
    private String YOUTUBE_VIDEO_ID = "EknEIzswvC0";
    private String YOUTUBE_PLAYLIST_ID= "PLS1QulWo1RIbb1cYyzZpLFCKvdYV_yJ-E";
    private Button btnPlayVideo;
    private  Button btnPlayplaylist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_standalone);
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        btnPlayplaylist= (Button) findViewById(R.id.btnPlayList);
        btnPlayVideo= (Button) findViewById(R.id.btnVideo);
        btnPlayVideo.setOnClickListener(this);
         btnPlayplaylist.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent= null;
        switch (v.getId()){
            case R.id.btnVideo:
                intent = YouTubeStandalonePlayer.createVideoIntent(this,GOOGLE_API_KEY,YOUTUBE_VIDEO_ID);
                break;
            case R.id.btnPlayList:
                intent = YouTubeStandalonePlayer.createPlaylistIntent(this,GOOGLE_API_KEY,YOUTUBE_PLAYLIST_ID);

                break;
            default:
        }

        if(intent!= null){
            startActivity(intent);
        }
    }
}

OUTPUT:
Now run the App and use the play the Youtube video you added.

10 thoughts on “How To Create Youtube Android App In Android Studio [Step By Step]”

  1. Hello abhi ;
    Thanks for your tutorials .

    If we develop an app to display a youtube videos with an admob ads , Is this match a google rules , legal licence to distribute it in the google market .

    Regards;
    Ahmed

    1. Hello. I want to know exactly how to integrate an admob account (banner and interstitials) into the whole youtube source code.

  2. i found an error while running the app

    WARNING: Configuration ‘compile’ is obsolete and has been replaced with ‘implementation’ and ‘api’.

      1. implementation replaced compile. period.
        api replaced a different keyword with a different purpose.

  3. i am new in android studio i dont know how to code pls need advice how to learn coding in android studio i love to learn programming

Leave a Reply

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

One More Step To Download Code...

SignUp! To Download Calculator App Code
Free Download Code Now >>
100% tested, easy instant download and import in Android Studio
close-link
JUST ONE MORE STEP TO COMPLETE...

Enter your email to get FREE exclusive Android App email tips:
SEND ME THE UPDATE
We hate SPAM and promise to keep your email address safe.
close-link
One More Step To Download Code...

SignUp! To Download WebView App Code
FREE DOWNLOAD CODE NOW >>
100% tested, easy instant download and import in Android Studio
close-link