There was a time where we had to use WebView to play YouTube videos in app. It worked, yes, but it was well clunky. WebView isn’t particularly known to have great performance, and you don’t have too much programatic control of the video itself.
But why would you use WebView now when you have access to the YouTube Android Player API? With the API, you can load and cue videos into a player view embedded in your app’s UI. You also have full programatic control in pausing, playing, and seeking to a specific point of the video.
The library itself is pretty light. Provided you’re using Proguard, it won’t add much at all to your app’s overall size.
The information in this post can all be found within the official docs so do check it out if you need to check things out in more detail.
Prerequisites
Before you can use the YouTube API, you need to register your app in the Google API Console, including your digitally signed apk file’s public certificate. Here’s how to do that.
- Go to the Credentials page of the Google API Console
- Using the Create Credentials button on top of the page, create either an OAuth 2.0 credential or an API key. An OAuth 2.0 is more appropriate if your app requests private user data. Otherwise, a simple API key will suffice.
- Go to the Library page of the console, search for, and enable YouTube Data API v3.
- After enabling the api, click the button which should now say “Manage”, go to the credentials section of the api management space, and ensure that the api key you created earlier is present.
Import the Library
As far as I’m aware of, you can’t use the standard method of importing via Gradle so you have to do it manually.
- Download the library from the official download page.
- Unzip the library and find the jar file inside the libs folder.
- Add the jar file to the libs folder of your project. You’ll find this folder by switching your folder structure from Android to Project.
- Right click to the jar file you added and select Add as Library.
This should let Android Studio automatically configure Gradle for you.
Usage
There are two ways to use the API. One is to use a YouTubePlayerView
inside an activity that extends YouTubeBaseActivity
, or to use a YouTubePlayerFragment
which is the preferred way. We’ll first do the former.
Using YouTubePlayerView directly
1. Add the Internet permission to your manifest.
<uses-permission android:name="android.permission.INTERNET"/>
2. Make your activity extend YouTubeBaseActivity
.
class MainActivity : YouTubeBaseActivity()
3. Include a YouTubePlayerView
in your view hierarchy.
<com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtube_player_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
4. Initialise your YouTubePlayerView
. You can also make your activity implement YouTubePlayer.OnInitializedListener
as an alternate way to perform this task (see step 3 of Using YouTubePlayerFragment below).
lateinit var youtubePlayer: YouTubePlayer private fun initYoutube() { youtube_player_view.initialize(getString(R.string.google_api_key), object: YouTubePlayer.OnInitializedListener { override fun onInitializationSuccess( provider: YouTubePlayer.Provider, player: YouTubePlayer, wasRestored: Boolean ) { youtubePlayer = player loadDoTheDogAvc() } override fun onInitializationFailure( provider: YouTubePlayer.Provider, error: YouTubeInitializationResult ) { handleError(error) } }) }
5. Use loadVideo(id: String)
to load your video of choice. The id you pass in is the id of the video on YouTube which you can find in the url of the video, or more reliably, when you click share, it’s the string after youtu.be/.
private fun loadDoTheDogAvc() { youtubePlayer.loadVideo("CjytAc-quyI") youtubePlayer.play() }
Now you should run your app and see the borkest video on YouTube play blissfully.
Using YouTubePlayerFragment
1. Add the Internet permission to your manifest.
<uses-permission android:name="android.permission.INTERNET"/>
2. Add a fragment to your view hierarchy with the name attribute set to YouTubePlayerFragment
.
<fragment android:id="@+id/youtube_fragment" android:name="com.google.android.youtube.player.YouTubePlayerFragment" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" />
3. Initialise your YouTubePlayerFragment
in an activity that extends YouTubeBaseActivity
. Here we also made the activity implement YouTubePlayer.OnInitializedListener
.
class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener { private fun initYoutube() { (youtube_fragment as YouTubePlayerFragment).initialize( getString(R.string.google_api_key), this ) } override fun onInitializationSuccess( provider: YouTubePlayer.Provider, player: YouTubePlayer, wasRestored: Boolean ) { this.youtubePlayer = player loadDoTheDogAvc() } override fun onInitializationFailure( provider: YouTubePlayer.Provider, error: YouTubeInitializationResult ) { } }
4. Use loadVideo(id: String)
to load your video of choice. The id you pass in is the id of the video on YouTube which you can find in the url of the video, or more reliably, when you click share, it’s the string after youtu.be/.
private fun loadDoTheDogAvc() { youtubePlayer.loadVideo("CjytAc-quyI") youtubePlayer.play() }
Now you should run your app and see the borkiest of the borks video on YouTube play borkfully.
A list of controls you can perform with YouTube Player
- Play
- Pause
- CueVideo
- CueVideos
- CuePlaylist
- LoadVideo
- LoadVideos
- LoadPlaylist
- SeekToMillis
- SeekToRelativeMillis
- SetFullscreen
- SetPlayerStyle
- Release
There are more methods of YouTubePlayer
than the ones above such as adding different sorts of listeners, so go check that class out.
Common issues
java.lang.SecurityException: Not allowed to bind to service Intent { act=com.google.android.youtube.api.service.START }
You didn’t add the Internet permission to the manifest.
kotlin.TypeCastException: null cannot be cast to non-null type com.google.android.youtube.player.YouTubePlayerFragment
Your activity doesn’t extend YouTubeBaseActivity
.
Limitations and Quotas
The YouTube Data API v3 we’re making use of does have some quotas to be aware of.
Although there are quite a number of them, the one to watch out most for is the quotas per day. This cap starts at 10,000 queries per day. One video may not necessarily mean a single query but in some cases, can mean hundreds. There’s no solid information out there as to how this works and really, the best way for you to manage this is see how it works for your app if the numbers are manageable.
You can request YouTube support to have an increased quota, of course, at a cost. Whether or not you’ll get a timely response is also debatable. Although I can’t vouch for this myself, there is no short of complaints to be found around Reddit, StackOverflow, and other forums.