Embedding YouTube Videos in Android Applications

YouTube is the largest video sharing platform in the world, so it makes sense to include its videos in a mobile app. In this article, I’m going to cover how to add them to your Android application using YouTube’s official API.

For the sake of this tutorial, we are going to start with an empty activity template, Kotlin, and a minimum API level of 6.0 in Android Studio.

Setup

Unfortunately, YouTube does not provide a Gradle dependency for its player API. This means we need to download it and include it in our project manually. The dependency can be downloaded here. Unzip the folder and place the YouTubeAndroidPlayerApi.jar anywhere in your project where it will not get deleted. I put mine in the app/libs directory at the root of my project.

Next, add the following line to your dependencies in your app/build.gradle file:

implementation files('libs/YouTubeAndroidPlayerApi.jar')

This gives you access to the YouTube API in your code.

Since the YouTube API requires internet, we need to add the following line to our AndroidManifest.xml under the <manifest /> tag.

<uses-permission android:name="android.permission.INTERNET"/>

Using the YouTubePlayerSupportFragment

The YouTubePlayerSupportFragment is the simplest option for embedding YouTube videos in an application. With it, you don’t need your activity to extend the YouTubeBaseActivity. Use the following XML snippet to add a YoutubePlayerSupportFragment to your layout:

<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="@+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

Our activity now needs to manage the fragment:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val youTubePlayerFragment = supportFragmentManager.findFragmentById(R.id.youtube_fragment) as YouTubePlayerSupportFragment;
    youTubePlayerFragment.initialize("xxxxxx", this);
}

In our activities onCreate method, we need to find the fragment in our layout and initialize it with an API key and an OnInitializedListener. In this case, our listener is the activity where the fragment is initialized. This requires our activity to override the following methods:

override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
    if(player == null) return
    if(wasRestored) {
        player.play()
    } else {
        player.cueVideo("oHg5SJYRHA0")
        player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
    }
}
override fun onInitializationFailure(provider: YouTubePlayer.Provider?, result: YouTubeInitializationResult?) {
    Log.d("Youtube Player", "Failed to initialize");
}

The cueVideo method tells the YouTubePlayer the ID of the video that you want to start playing. The ID is located at the end of a video’s URL, like this: https://www.youtube.com/watch?v=VIDEO_ID.

Next, we tell the YouTube Player to use the default style. More styles and their explanations can be found here.

It’s also critical to check the wasRestored flag so users can view the video in full-screen format. If you do not check whether the YouTube Player was restored, the video will restart from the beginning when a user presses the full-screen button.

Using the YouTubeStandalonePlayer

If you don’t need the video embedded within your app, the YouTubeStandalonePlayer is another great option. It allows you to open a separate activity that shows your desired video in horizontal full-screen format.

val intent = YouTubeStandalonePlayer.createVideoIntent(this, "XXXX", "oHg5SJYRHA0");
startActivity(intent);

Conclusion

If you’re interested, you can read the documentation for the YouTube Player API and see an example project for the code. The fragment example is in the xml branch, and the stand-alone player example is in the standalone branch.