In this tutorial we are going to learn how to play YouTube video in the app. This article covers very basics of YouTube Android API. If you want refer youtube API in developer, please go through Android Youtube API docs provided by Google.
As we are interacting with Google APIs, we need to get the Google Developer API Key first. Follow below steps to obtain your Google Developer Android API Key.
1. Android API Key
1. First we need to get the SHA-1 fingerprint on your machine using java keytool. Execute the below command in cmd/terminal to get the SHA-1 fingerprint.
On Windows
keytool -list -v -keystore "your android\degug.keystore path" -alias androiddebugkey -storepass android -keypass android |
2. Go to Google Developer Console and select or create a new project. And turn the status ON for YouTube Data API v3.
3. On the left sidebar, select Credentials and Create new key.
4. When popup comes asking you to choose platform, select Android Key.
5. Paste the SHA-1 key and your project’s package name
6. Click on create. Now you should see the API KEY on the dashboard.
2. Creating the Android Project
1.In Android studio create a new android project by navigating to File ⇒ New ⇒ Android Application Project and fill out all the required details.
2. Download the latest of version of YouTube Android Player API - Download and extract it. Once extracted, you can find YouTubeAndroidPlayerApi.jar file inside libs folder.
3. Paste the YouTubeAndroidPlayerApi.jar file in your project’s libs folder.
4. Create a class named Constants.java to keep our app configuration variables like Google Developer Key.
In Constants.java class, you need to replace the DEVELOPER_KEY with your own API KEY that we generated in the Google Developer Console.
Constants.java
public class Constants{
// Google Console APIs developer key
// Replace this key with your's
public static final String DEVELOPER_KEY = "xxxxxxxxxxxxxxxxx";
}
5.Now open the layout file of your main activity (activity_main.xml) and add below code. This creates a simple layout with YouTubePlayerView.
activity_main.xml
<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"> <LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:background="@drawable/rouned_corner_shadow"android:gravity="center_horizontal"android:orientation="vertical"> <com.google.android.youtube.player.YouTubePlayerViewandroid:id="@+id/youtube_video_player"android:layout_width="match_parent"android:layout_height="match_parent"android:visibility="visible"> </com.google.android.youtube.player.YouTubePlayerView> </LinearLayout> </RelativeLayout>
6. Open your main activity class (MainActivity.java) and do the below simple changes. Here the activity is extended from YouTubeBaseActivity which will be present in YouTubeAndroidPlayerApi.jar. In case your not extend YouTubeBaseActivity application will not run..
7.If your don't have any youtube_ID fetch it from youtube url using getYouTubeId() function.
7.If your don't have any youtube_ID fetch it from youtube url using getYouTubeId() function.
MainActivity.java
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; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener { private static final int RECOVERY_DIALOG_REQUEST = 1; private YouTubePlayerView youTubeView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_video_player); // Initializing video player with developer key
youTubeView.initialize(Constants.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( getString(R.string.error_player), 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
// if you have Youtube_Id pass directly here
player.loadVideo("Youtube_ID");
// If you don't have youtube ID get it from youtube url using this methos
//player.loadVideo(getYouTubeId("Youtube_URL"));
// 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); } private String getYouTubeId(String youTubeUrl) { String pattern = "(?<=youtu.be/|watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*"; Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher = compiledPattern.matcher(youTubeUrl); if (matcher.find()) { return matcher.group(); } else { return "error"; } }
No comments:
Post a Comment