Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

YouTube Video in Android App using YouTube Player API

YouTube Video in Android App using YouTube Player API
Hello Guys. Welcome to our new tutorial of YouTube Video in Android App using YouTube Player API. Here we will teach you how to play a YouTube video in an android App. So here YouTube will be embedded in Android App itself. This we will do through Youtube Player API developed by google. You can read more about it here. Major application of android youtube player is that now you can directly upload video to YouTube and stream it in your App. You can see demo of this youtube android player api example below:

Demo of YouTube Video in Android App using YouTube Player API




Download full code here:

What is Youtube Player API

It allows us to incorporate video playback functionality in an Android App. Youtube Player API consist of methods that control loading and playing videos along with customizing playback experience. Now we can easily cue different YouTube videos in an Android App UI and control playback in a programmatic manner.It also supports orientation and transition but that part won’t be covered in this tutorial. Take that as your Homework ;).

How Youtube Player API Works

As can be seen in Google developer guide, The API client library interacts with a service that is distributed as a part of the YouTube app for the Android platform.The client library has a light footprint, meaning it won’t adversely impact our app’s file size, if we use ProGuard as part of build process.

Let’s start making Android YouTube Player using Youtube Player API. We hope you will enjoy it.:)

Generate YouTube API Key

1) First we need get the SHA-1 fingerprint on our machine using java keytool. Execute the below command in cmd/terminal to get the SHA-1 fingerprint.

On Linux or Mac

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

On Windows

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

You will see following image:

2) Now go to Google Developer Console and create a new project. Here click on Credentials on left bar as shown below:

3) Click on Create Credentials and select API Key as shown below:

4) After creating API Key, click on RESTRICT KEY as shown below:

5) Now add package name and SHA-1 fingerprints (These finger prints will be the one which we created in 1st step) and click Save as shown below:

So our API key is ready. Please copy it.

Creating a New Project – YouTube Player API

  1. Open Android Studio and create a new project YouTube Player API and company domain application.example.com (We have used our own company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  2. Click Next and choose Min SDK (It should be maximum possible). Again Click Next and Choose Blank Activity .
  3. Choose the Activity as MainActivity and click next.
  4. Leave all other things as default and Click Finish.
  5. Download the latest version of YouTube Player API from here and extract it.
  6. After extraction, you will see a jar file inside libs folder. Copy this jar file and paste it at path …/YouTubePlayerAPI/app/libs/. Project Structure now look like as follows:
  7. Now that library is added, we have to make sure that build.gradlefile has following declaration for jar file:
  8. dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        //... other dependencies
    }
    

    Now select Tools > Android > Sync Project with Gradle Files option on Android Studio menu to sync project after adding jar file.

So finally we are done with all project requirements. Now let’s start coding our Android youtube player.

Adding Internet Permissions

Add internet permissions in AndroidManifest.xml:

Layout of Android youtube player

Add following code inside activity_main.xml

activity_main.xml


Adding Youtube API key in Android Project

Create a new java file named config.java at path where MainActivity.java is stored (…/YouTubePlayerAPI/app/src/main/java/com/androidtutorialpoint/youtubeplayerapi/config.java) and add following code:

config.java

package com.androidtutorialpoint.youtubeplayerapi;

/**
 * Created by navneet on 24/12/16.
 */

public class config {
    // Google Console APIs developer key
    // Replace this key with your's
    public static final String DEVELOPER_KEY = "AIzaSyBadTmaKq4acMyfWWtwyT3ERyuC-0PxoqA";

    // YouTube video id
    public static final String YOUTUBE_VIDEO_CODE = "EArO6h1qPJE";
}

In the above code we have added the key we generated at the start of tutorial. Please add that key as DEVELOPER_KEY. Also YOUTUBE_VIDEO_CODE is the YouTube video id to be played in Android App.

Playing YouTube video in Android App

Finally we will give main functionality to our project by adding following code in MainActivity.java

MainActivity.java

package com.androidtutorialpoint.youtubeplayerapi;


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(
                    "There is an error in playing YouTube Video: %s", 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);
    }

}

In the above code we have extended our MainActivity from YouTubeBaseActivity to directly incorporate YouTubePlayerView. After successful initialization,function onInitializationSuccess function will get created where we have loaded our video through player.loadVideo(config.YOUTUBE_VIDEO_CODE);. Also in the onCreate method we have written youTubeView.initialize(config.DEVELOPER_KEY, this) to instantiate YouTubePlayer.

Now you can run this project. Now will see a YouTube video running in android app. You can see its demo in the YouTube video given at start of tutorial. So our tutorial of YouTube Video in Android App using YouTube Player API is complete. You can also customize this YouTube video player as shown below.

Customized Android YouTube Player

The YouTube Player API allows us to customize playback controls by setting player.setPlayerStyle() in onInitializationSuccess:

1) YouTubePlayer.PlayerStyle.DEFAULT : It is a default style which will show all controls as can be seen in any YouTube Video.

2) YouTubePlayer.PlayerStyle.MINIMAL : This only display a time bar and play/pause controls.

3) YouTubePlayer.PlayerStyle.CHROMELESS : This is what we have used in our project. Here we need to write our own controls.




What’s Next ??

You can see our other tutorials on material design like Android ScrollView, ViewPager and Expandable ListView Tutorials etc.

We hope you liked our tutorial of YouTube Video in Android App using YouTube Player API, please leave comments in the comment section below in the case of any doubts. Let us know how do your views on it.

To download the full code of this tutorial, Click on the Download Now link below.


The post YouTube Video in Android App using YouTube Player API appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

YouTube Video in Android App using YouTube Player API

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×