Thursday, June 20, 2013

Simple example using YouTube Android Player API

Simple example using YouTube Android Player API

Before create app using YouTube Android Player API, you have to "Download and import YouTube Android Player API" and "Register your app using YouTube Android Player API and obtain API Key".

Modify layout xml to add view of <com.google.android.youtube.player.YouTubePlayerView>.
<LinearLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold"
        android:layout_gravity="center_horizontal"
        android:autoLink="web" />
    
    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/youtubeplayerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


Modify MainActivity.java, extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener.
package com.example.androidyoutubeapiplayer;

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{
 
 public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
 public static final String VIDEO_ID = "o7VVHhK9zf0";

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

 @Override
 public void onInitializationFailure(Provider provider,
   YouTubeInitializationResult result) {
  Toast.makeText(getApplicationContext(), 
    "onInitializationFailure()", 
    Toast.LENGTH_LONG).show();
 }

 @Override
 public void onInitializationSuccess(Provider provider, YouTubePlayer player,
   boolean wasRestored) {
  if (!wasRestored) {
        player.cueVideo(VIDEO_ID);
      }
 }

}


Where API_KEY is the key obtained in the step of "Register your app using YouTube Android Player API and obtain API Key", VIDEO_ID is the ID of the video to play.

Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidyoutubeapiplayer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <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="com.example.androidyoutubeapiplayer.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>



download filesDownload the files.

Download APK to try on your device.

Next: YouTubeThumbnailView example of YouTube Android Player API

Related: YouTube Android Player API step-by-step

18 comments:

RENOL SAM said...

showing "error on initilisation of player"

Cristiana M. said...

it doesnt work, it says an error occured while initializing the player.

Anonymous said...

It works .. thanks ...for error on initialisation of player ... u must have made smthn wrong with the jar file ... reread instructions and redo

Raam Kumar said...

To run this app, Users need to run version 4.2.16 of the mobile YouTube app (or higher).Otherwise you will get "error on initilisation of player".

Anonymous said...

I am not sure where to place the xml with the id 'youtube_player'
Does it replaced the generated activity_main.xml frame layout?

Andr.oid Eric said...

hello Anonymous,

yes.

Ratna Deep said...

Thanks for BLOG really gr8 blog.
I want to know if youtube app is not install then how can i play youtube videos.


Thanks

Hnin Wut Yee said...

I want three you tube video or in one page..How to do it

Mohit Suthar said...

Can we implement without extend this YoutubeBaseActivity ?
Thanks

Ranjith sp said...

pls help me how to load multiple videos thumbnail and play eveyone

achola sam said...

private YouTubePlayer.Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return (YouTubePlayerView)findViewById(R.id."your_xml_id");
}

This worked for me.

Kuldeep Kumar said...

will it work if I use eclipse and emulator, since I don't have any android phone. It's giving failure to initialize when I run in emulator, any specific emulator settings?

Chí Trịnh Minh said...

Interesting example!

Anyway, I couldn't play private video Id with this, is there any way that we can authenticate and play private videos using YoutubePlayerView?

Thanks in advanced.

rahmat setyawan said...

I am problem when i run in hp. message error "java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.video_streaming/com.example.video_streaming.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.video_streaming.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.video_streaming-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.video_streaming-2, /vendor/lib, /system/lib]]"

steps I have done is in conformity with the tutorial. Please give a solution for those who have managed to do this tutorial

ששי מועלם said...

any body can explain me what wrong ? its not work !! this is my code


"package evt.co.il.evtfamily.androidyoutubeapiplayer;

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.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

import evt.co.il.evtfamily.R;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{

public static final String API_KEY = "AIzaSyAyfTfH50eIggZZCcwE85wgMq0dS4XKfl0";
public static final String VIDEO_ID = "o7VVHhK9zf0";

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

YouTubePlayerView youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_LONG).show();
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}

}

joatmon said...

Great post. Very simple. Thanks!

dina saif said...

thanks it works
try it in your mobile it will work

Fabio De Lorenzo said...

Thanks a lot. This example is much cleaner than the one on the youtube developer site.

Thanks,
Fabio