Apps

Using Google's YouTube API in your Android apps

Explore how to embed YouTube videos in your Android apps using Google's new API.

While I'm an admitted Android fanboy, I am not above acknowledging areas where the platform could use improvement. In the past, one of these shortcomings in Android's offerings for developers has been integration with YouTube. This is a particularly painful point for us fanboys because A) both Android and YouTube are Google projects, and B) my colleagues who work primarily on iOS have had a relatively consistent and pleasant integration experience with YouTube for some time now using iPhone's standard webview component.

Luckily, the engineers at Google have been working hard behind the scenes. Now at version 3.0 and free of the "experimental" label, Google hails its YouTube API to be ready for prime time. The documentation promises: "...the API lets your application provide a full-fledged YouTube experience that includes search and discovery, content creation, video playback, account management, and viewer statistics."

I don't know about you, but I'm ready for a test drive!

1. You will need a mobile device running version 4.2.16 or better of the official YouTube app. That's right, the underlying service used by the Android YouTube Client API is distributed along with the actual YouTube application for Android. The lack of separation was a little disheartening to me, but Google claims the necessary scaffolding should be available for all devices running Android 2.2 or higher, and bundling the service with the app reduces overall footprint on the device.

2. Next you need an API key. It's free, but you need your Google account to get it. If you want to run the sample demo that follows, you will need to get an API key (since I don't plan on sharing mine with the entire Internet). You can find detailed instructions here. (If you don't want to take the time to submit an SHA 1 Fingerprint Certificate, you can leave the field blank for the time being, and the API will accept all your calls. Just be sure to go back and restrict it to your own package/apps before releasing anything into the wild.)

3. After you register for an API key, you are ready to open Eclipse and start a new Android project.  Remember to target at least Android 2.2.

4. Before going on we need to download the client library files. Unzip the compressed folder, locate the YouTubeAndroidPlayerApi.jar (Figure A), and add it to your project's /libs folder. Figure A

5. Right-click the jar file, then go to Build Path | Configure Build Path. Click the Add JARs button (Figure B). Figure B

6. From the JAR Selection dialog, navigate to the recently copied jar file and select it (Figure C). Figure C

7. Next we need to open the project's AndroidManifest.xml file and add the Internet permission.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.authorwjf.youtubeapi"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.authorwjf.youtubeapi.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>

8. We modify the /res/layout file to include the YouTubePlayerView from the newly added jar file.

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center_horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello YouTube API"
        android:layout_margin="12dip"/>
   <com.google.android.youtube.player.YouTubePlayerView
              android:id="@+id/youtube_view"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_margin="12dip"/>
</LinearLayout>

9. We can access the component from our src file by extending the YouTubeBaseActivity.

MainActivity.java
package com.authorwjf.youtubeapi;
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;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {

static private final String DEVELOPER_KEY = "add your own key here!";
       static private final String VIDEO = "4SK0cUNMnMM";
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              YouTubePlayerView youTubeView = (YouTubePlayerView)
findViewById(R.id.youtube_view);
           youTubeView.initialize(DEVELOPER_KEY, this);
          }
         @Override
         public void onInitializationFailure(Provider provider,
YouTubeInitializationResult error) {
                Toast.makeText(this, "Oh no! "+error.toString(),
Toast.LENGTH_LONG).show();
       }
       @Override
       public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
              player.loadVideo(VIDEO);
       }
}
As you can see, it is the setup, not the actual code, that represents the majority of the work. Despite the documentation suggesting the player view would work on the Android emulator, I was not able to find a platform where that was the case even after updating all my tools and SDKs to the latest and greatest releases (Figure D). Figure D

Fortunately, the application did seem to work well on my Nexus 4 hardware (Figure E). Figure E

My final thoughts

Unfortunately, the API still seems a bit complicated to me -- less so on the programming side and more on the setup. However, it appears to work on my device (if not the emulator), so if further testing shows it to work consistently across the Android hardware landscape, I am willing to invest the extra effort.

For those of you who'd like to try this project on your own devices, you can download it here. Just remember, you must register for your developer API code and insert it into the MainActivity.java file before the app will work.

About

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

11 comments
data2700
data2700

Thank you, this tutorial was excellent and to the point.  I looked around the internet for this and your tutorial is the only explanation of getting started with the youtubeAPI that made sense and had code that just worked.  Well done.

supertiger1234
supertiger1234

ITS TO CONPLITATED AGRRR PLZZ MAKE AYOUTUBE VIDEO PLZZZZZA

supertiger1234
supertiger1234

PLZZZ CAN U MAKE A VIDEO ITS COMPLICATED! PLZZZ NAHGGEGEEG!

SohailAziz
SohailAziz

Thanks for great post. Code working fine for normal youtube videos but not working for Live streams. Is live streaming supported by API?

bkothari99
bkothari99

Your code working nice but when I try to integrate google Admob banner then I getting error like java.lang.RuntimeException: Unable to start activity ComponentInfo{com.authorwjf.youtubeapi/com.authorwjf.youtubeapi.MainActivity}: android.view.InflateException: Binary XML file line #22: Error inflating class com.google.ads.AdView and its unfortunately shutting down. Can U some one help me to solve this problem?

atoms
atoms

Thanks Wiz, but it turned out that the version of the You Tube app on the device was too old. It was 2.* and it needs to be 4.2.16 uh, as was clearly stated in the article.

atoms
atoms

It isn't working for me. Even on a device I'm getting the same error as you got on your emulator: "An error occurred while initializing the YouTube player." There is also a brief "Oh no SERVICE_VERSION_UPDATE_REQUIRED" displayed. The developers.google.com docs at https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubeInitializationResult claim that this error is a result of "The installed version of YouTube API service is out of date." hmm...

authorwjf
authorwjf

Are you using the latest Admob library? My project was compiled against the base SDK (not including the Google API's). My suggestion would be to create your own project with Admob then once that is working paste in the Youtube code and manually pull in the associated JAR file.

wizard57m-cnet
wizard57m-cnet

as Google and Microsoft recently had a spat over the YouTube player in the Windows App Store, built on the old API, that didn't show the advertisements! May need to check the repository and see if an updated API is available, I've read that MS has updated the Windows Store app.

Editor's Picks