The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications. The API allows you to load and play YouTube videos (and playlists) and to customize and control the video playback experience.
You can load or cue videos into a player view embedded in your application’s UI. You can then control playback programmatically. For example play, pause, or seek to a specific point in the loaded video. You can register event listeners to get callbacks for certain events, such as the player loading a video or the player state changing. The API also has helper functionality to support orientation changes as well as transitions to fullscreen playback.
Before using the Android Youtube API, you need to register your application, including your digitally signed .apk file’s public certificate in the Google Developers Console. To register the application, follow these steps.
Go to the Google Developers Console
Create a new project. I named mine VideoTube.
In the sidebar on the left, make sure that Library is selected. On the right panel, select the Youtube Data API and Enable it on the page that follows.
In the sidebar on the left, select Credentials. For credentials, the API supports OAuth 2.0, the use of an API key and of a Service account. We’ll use the API key option.
Select API key from the Create Credentials dropdown menu. A popup will appear with the value of your API key. Keep this window open, we’ll use the key in the next step.
1 2 3 4 5 6 7 8 9 10 |
package com.codezlab.youtubeplayer; /** * Created by coderzlab on 24/5/17. */ public class Constants { public static final String YOUR_YOUTUBE_KEY=""; } |
Paste in your API key.
Download the latest version of the YouTube Android Player API (1.2.2 at the time of writing). Unzip the downloaded file to find the library jar file and a sample application that you can use to see what the library offers. The jar file is located in the libs folder. Copy and paste it into your project’s libs folder. To access the libs folder, use the Project perspective on the Android Studio Project Explorer. Then expand VideoTube -> app -> libs.
1 |
compile fileTree(dir: 'libs', include: ['*.jar']) |
Sync the project’s gradle files.
Add the following permission for internet access to the AndroidManifest.xml file as a child of the manifest tag and a sibling to the application.
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
Now create a YoutubePlayerActivity.java in file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
package com.codezlab.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.YouTubePlayerView; public class YoutubePlayerActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 1; // YouTube player view private YouTubePlayerView youTubeView; String videourl; @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.player_activity_layout); Intent in = getIntent(); videourl = in.getStringExtra("videourl"); youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); // Initializing video player with developer key youTubeView.initialize(Constants.YOUR_YOUTUBE_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("error_player"); 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 //String[]videocode = videourl.split("="); player.loadVideo(videourl); } } @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(Constants.YOUR_YOUTUBE_KEY, this); } } private YouTubePlayer.Provider getYouTubePlayerProvider() { return (YouTubePlayerView) findViewById(R.id.youtube_view); } } |
Next we’ll add a YouTubePlayerView to the layout file. This view is used for displaying YouTube videos.
add player_activity_layout.xml in layouts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black" android:gravity="center" android:orientation="vertical"> <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
Now its time to modify MainActivity’s Layout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.codezlab.youtubeplayer.YoutubePlayerActivity"> <Button android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/playBT" android:text="play now" android:textAllCaps="true" /> </RelativeLayout> |
and also you need to modify MainActivity Contents.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.codezlab.youtubeplayer; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_player); findViewById(R.id.playBT).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { playNow(); } }); } private void playNow(){ /* * Youtube video Url : * https://www.youtube.com/watch?v=fURkRSbO20k * * you need to pass only video id to play it */ Intent intent=new Intent(MainActivity.this,YoutubePlayerActivity.class); intent.putExtra("videourl","fURkRSbO20k"); startActivity(intent); } } |
Now you have done with your code and you can start with playing Youtube videos in your app.
Thanks for reading.
1 Comment
Abdul Mueed
Nice tutorial it really helped me.