How to Play YouTube Video in Android App

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.
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newfrndroid_footer1_AdSense3_970x90_as -->
<ins class="adsbygoogle"
     style="display:inline-block;width:970px;height:90px"
     data-ad-client="ca-pub-1660966374593262"
     data-ad-slot="6385754437"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

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

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newfrndroid_footer1_AdSense3_970x90_as -->
<ins class="adsbygoogle"
     style="display:inline-block;width:970px;height:90px"
     data-ad-client="ca-pub-1660966374593262"
     data-ad-slot="6385754437"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
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 Projectand 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.
strings.xml
<?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.
color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="shadow">#555555</color>
    <color name="title">#777777</color>
</resources>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newfrndroid_footer1_AdSense3_970x90_as -->
<ins class="adsbygoogle"
     style="display:inline-block;width:970px;height:90px"
     data-ad-client="ca-pub-1660966374593262"
     data-ad-slot="6385754437"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
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.
Config.java
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.
rouned_corner_shadow.xml
<?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>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- newfrndroid_footer1_AdSense3_970x90_as -->
<ins class="adsbygoogle"
     style="display:inline-block;width:970px;height:90px"
     data-ad-client="ca-pub-1660966374593262"
     data-ad-slot="6385754437"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
9. Now open the layout file of your main activity (activity_main.xml) and add below code. This creates a simple layout with YouTubePlayerView.
activity_main.xml
<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 inYouTubeAndroidPlayerApi.jar. This activity also contains few initialization listener methods to know the status of the youtube player.
MainActivity.java
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.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    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.
android playing youtube video
Share on Google Plus

We work hard for you. One Like Please?

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment