Play YouTube video in Android using YouTube player API

Play YouTube video in Android using YouTube player API

In this tutorial we are going to learn how to play YouTube video in Android using YouTube player API. If you are not planning to use YouTube player API, I wrote a tutorial on how to embed YouTube video in android WebView and How to play YouTube video inside Android WebView using Video Url.

The YouTube Data API v3 is an experimental API that provides access to YouTube data, such as videos, playlists, and channels. If you are planning to retrieve different data from YouTube videos, the YouTube Data API is the best way to go.

In other to use the YouTube Data API v3, you have to obtain request API key from Google API developers console. There are two different authentication method – Oauth 2.0 and API Keys. The Oauth 2.0 is use to access private data while the API keys is for public information.

We are going to use the API keys in this tutorial.

Follow the steps below to register and obtain your API key.

1. Go to the Google Developers Console.

2. Select a project.

3. In the sidebar on the left, select APIs & auth. In the list of APIs, make sure the status is ON for the YouTube Data API v3.

Play YouTube video in Android using YouTube player API

4. In the sidebar on the left, select Credentials.

5. API keys: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports. If the key type you need does not already exist, create an API key by selecting Create New Key and then selecting the appropriate key type. Then enter the additional data required for that key type.

6. Use an Android key if your application runs on Android devices

Play YouTube video in Android using YouTube player API

7. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file’s public certificate.

keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

Play YouTube video in Android using YouTube player API

Now that we have obtain the API key, we will move ahead to create our android application.

Before we start, the first thing I will do is to list the environment and tools I used in this android tutorial but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidYouTubePlayerAPI

Package: com.inducesmile.androidyoutubeplayerapi

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

Since we are going to use the YouTube Player API, we will download the .jar file from Google developers website.

Once downloaded, we will import the .jar library file to our android project. If you are using Android studio, you can read my post on how to add .jar file in android studio project.

Since the application will make use of internet, we are going to add the internet permission in our Manifest.xml file. The updated version of our Manifest file is shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="inducesmile.com.androidyoutubeplayer" >
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>

 activity_main.xml

Open activity_main.xml file and add the YouTubePlayerView which is the View that is use to display the YouTube Player. Copy and paste the following xml code in your activity_main.xml file.

<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"
    tools:context=".MainActivity">

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtube_player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp" />

</RelativeLayout>

 MainActivity.java

Our MainActivity class will extends the YouTubeBaseActivity class and will also implements YouTubePlayer.OnInitializedListener.

We will get the instance of our YouTubePlayerView using the activity method findViewById();

We will create two final string that will hold our API key and video id. We will override two methods – onInitializationSuccess() and onInitializationFailure().

In the onCreate method of the activity class, we will use the YoutubePlayerView object method initialize() and the API key and the application context is passed as parameters to this method.

The code for the MainActivity.java file is as follow.

package inducesmile.com.androidyoutubeplayer;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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.Provider;
import com.google.android.youtube.player.YouTubePlayerView;


public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {

    private static final String API_KEY = "API KEY";
    private static final String VIDEO_ID = "7bDLIV96LD4";
    private YouTubePlayerView videoPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoPlayer = (YouTubePlayerView)findViewById(R.id.youtube_player);
        videoPlayer.initialize(API_KEY, this);
    }

    @Override
    public void onInitializationSuccess(Provider provider, YouTubePlayer youTubePlayer, boolean complete) {
        if (!complete) {
            youTubePlayer.cueVideo(VIDEO_ID);
        }
       // youTubePlayer.loadVideo(VIDEO_ID);
    }

    @Override
    public void onInitializationFailure(Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        Toast.makeText(MainActivity.this, youTubeInitializationResult.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Save the file and run your project. If everything works for you, the project will appear like this in your device.

youtubeapi

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

OTHER INTERESTING POSTS:

One Response

Add a Comment