-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Streaming Youtube Videos with YouTubePlayerView
To stream YouTube videos inside an Android app, the current honest options are the official YouTube IFrame Player API (YouTube's own web player, embedded in a WebView) or — much more conveniently — the actively maintained open-source android-youtube-player library, which wraps the IFrame player in a native YouTubePlayerView with a Java/Kotlin API. Because the library plays videos through YouTube's own web player, it is compliant with the YouTube terms of service.
⚠️ Google's official YouTube Android Player API has been discontinued — its documentation andYouTubeAndroidPlayerApi.jardownload pages have been removed. This guide previously walked through that library; the old steps are preserved at the bottom of the page under Historical reference for legacy apps that still ship the JAR.
Add the library to your app module's build.gradle (it is published on Maven Central; version 13.0.0 was released in September 2025 and the library requires minSdk 21):
dependencies {
implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:13.0.0'
}Unlike the discontinued official library, no API key, Google Play services, or installed YouTube app is required — the player runs in a WebView under the hood, so it works on any device or emulator with a WebView.
Add a YouTubePlayerView to your layout where you'd like the video displayed:
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
android:id="@+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />Your Activity does not need to extend any special base class. Register the view as a lifecycle observer (so it releases the player automatically) and load a video by its YouTube video id (do not include the full URL):
class QuickPlayActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quick_play)
val youTubePlayerView = findViewById<YouTubePlayerView>(R.id.youtube_player_view)
lifecycle.addObserver(youTubePlayerView)
youTubePlayerView.addYouTubePlayerListener(object : AbstractYouTubePlayerListener() {
override fun onReady(youTubePlayer: YouTubePlayer) {
youTubePlayer.loadVideo("5xVh-7ywKpE", 0f)
}
})
}
}public class QuickPlayActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_play);
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view);
getLifecycle().addObserver(youTubePlayerView);
youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() {
@Override
public void onReady(@NonNull YouTubePlayer youTubePlayer) {
youTubePlayer.loadVideo("5xVh-7ywKpE", 0f);
}
});
}
}If you wish to only load the video but not start playback, use cueVideo(videoId, startSeconds) instead of loadVideo(videoId, startSeconds).
For simple cases you can even skip the listener entirely and autoplay straight from XML with the app:videoId and app:autoPlay attributes on the YouTubePlayerView. The library README documents the full API, including full-screen support, custom player UI, playback state tracking, and a Chromecast extension module.
If you wish to force the video to landscape mode, you can also add the screenOrientation flag inside your Activity in the AndroidManifest.xml file:
<activity
android:name=".QuickPlayActivity"
android:screenOrientation="landscape">
</activity>Deprecated: everything below documents the discontinued official YouTube Android Player API (
YouTubeAndroidPlayerApi.jar,YouTubeBaseActivity,com.google.android.youtube.player.YouTubePlayerView). Google has removed its documentation and download pages, so these steps cannot be followed for a new project — they are preserved only for maintaining legacy apps that still bundle the JAR.
In order to use this API, you will need to have Google Play installed on your emulator and the Youtube App installed because the YouTube API interacts with a service that is distributed with the YouTube app. Either use a physical device to test or make sure you have followed this emulator setup guide to install Google Play services and then added the Youtube App. Otherwise, you are likely to see An error has occurred while initializing the YouTube player.
To start, you needed an API key created through https://console.developers.google.com/ with the YouTube Data API v3 enabled (Credentials section => generate an API key).
Next, the YouTubeAndroidPlayerApi.jar file (download no longer available) had to be added to the app's libs dir by following this GIF. Once the JAR was added, selecting Tools => Android => Sync project files with Gradle in Android Studio completed the installation.
To ensure that the Youtube player could also be successfully initialized on devices running API 30+, the following was also needed in AndroidManifest.xml:
<queries>
<intent>
<action android:name="com.google.android.youtube.api.service.START" />
</intent>
</queries>Instead of a VideoView, a YouTubePlayerView went in the layout file where the video should be displayed:
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>The hosting Activity had to extend YouTubeBaseActivity. One drawback is that this base class does not inherit from AppCompatActivity, so some styles defined in styles.xml may not apply.
public class QuickPlayActivity extends YouTubeBaseActivity {The YouTube Player was then initialized by calling initialize() with the API key on the YouTubePlayerView:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_play);
YouTubePlayerView youTubePlayerView =
(YouTubePlayerView) findViewById(R.id.player);
youTubePlayerView.initialize("YOUR API KEY",
new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
// do any work here to cue video, play video, etc.
youTubePlayer.cueVideo("5xVh-7ywKpE");
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
}Calling cueVideo() loaded the video without playing it, while loadVideo() started playback, passing along the YouTube video key (not the full URL):
youTubePlayer.loadVideo("5xVh-7ywKpE");Alternatively, rather than extending YouTubeBaseActivity, the legacy library also offered a YouTubePlayerFragment (reference docs no longer available). First, the player went into the activity using this fragment:
<fragment
android:id="@+id/youtubeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.google.android.youtube.player.YouTubePlayerFragment">
</fragment>Next, we lookup the fragment by ID and then initialize the video player:
@Override
protected void onCreate(Bundle savedInstanceState) {
YouTubePlayerFragment youtubeFragment = (YouTubePlayerFragment)
getFragmentManager().findFragmentById(R.id.youtubeFragment);
youtubeFragment.initialize("YOUR API KEY",
new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
// do any work here to cue video, play video, etc.
youTubePlayer.cueVideo("5xVh-7ywKpE");
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
// ...
}Note that in this case, the activity containing the fragment does not need to extend any special base class. Otherwise the steps are identical regardless of using the fragment or activity approach.
Common issues with the legacy com.google.android.youtube.player.YouTubePlayerView are listed below:
-
Setup Youtube App - In regards to setup, if you are using an emulator, make sure you have followed this emulator setup guide to install Google Play services and then also added the Youtube app. Otherwise, you are likely to see
An error has occurred while initializing the YouTube player. -
Verify Video is Valid - When anything is going wrong, first thing to check that the value passed into the
cueVideoorloadVideomethods is a valid Youtube video. Be sure not to pass a null value into those methods. Investigate to make sure that if you take the value given i.e5xVh-7ywKpEand then visit this on youtube that the video is valid. -
NullPointerException During Init - Make sure that your activity
extends YouTubeBaseActivityor you are using theYouTubePlayerFragment. If the activity does not extend that base class then the activity will throw this exception. -
Error DeadObjectException: If you receive the
java.lang.IllegalStateException: android.os.DeadObjectExceptionexception, you need to open up the "Play Store" and update the Youtube app on the Android device. -
Error Leaked ServiceConnection: If you are using an emulator, upgrade to Lollipop (API 21) and open up the "Play Store" to check for updates to the Youtube app.
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.