How to embed YouTube videos into your Android app using Kotlin

How to embed YouTube videos into your Android app using Kotlin

In this tutorial, I’m going to show you how to embed a youtube video in your android app with three different methods, using the official library (YouTube Player API), a 3rd party library called Android YouTube Player, and WebView.

1st Method (YouTube Player API)

Pros
  • Official library provided by YouTube
Cons
  • Has bugs that haven’t been fixed since 2015
  • Need an API KEY
  • Doesn’t get updates anymore
  • You have to calculate the aspect ratio of the video manually

YouTube Player API is the official way to embed a youtube video in your android app, the problem with this library is they don’t maintain it anymore, the latest update was in 2015 (1.2.2 version), but besides that, it’s a recommended method if you don’t want to display a lot of videos in your app.

Get the API KEY from Google

First, we have to get our API key from the Google Developers Console.

Let’s create a project by pressing the ‘CREATE‘ button:

In the new window, type a name for the project and press ‘CREATE‘:

Go back to the Dashboard and press the ‘ENABLE APIS AND SERVICES‘ button:

Now, we have to find the YouTube Data API v3, use the search bar at the top of the screen to find it quicker, and enabled it:

Now, choose Credentials on the left sidebar and press Create credentials.

In the dropdown menu, choose API KEY:

Done! Now we have generated our API KEY and it’s ready to use it in our embed YouTube Player later.

Add YouTube Player API into our app

First, we have to add the library to our project. Let’s go and download the jar file from here.

After you downloaded it, unzip it, and go to the libs folder and copy the YouTubeAndroidPlayerApi.jar file.

Now go to our project and change from Android to Project in the dropdown menu and paste the jar file like that:

Now, let’s insert the libs folder (if it does not already exist) in our project by adding the following line in our build.gradle file:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

Now it’s time to add the YouTube player view to our layout, by adding it like that:

<?xml version="1.0" encoding="utf-8"?>
<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"
        android:background="@color/colorPrimary"
        tools:context=".YouTubePlayerAPIActivity">

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

</RelativeLayout>

Let’s go to our Kotlin class with the YouTube view and add the following code:

class YouTubePlayerAPIActivity : AppCompatActivity(), YouTubePlayer.OnInitializedListener {


    private val RECOVERY_DIALOG_REQUEST = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_youtube_player_api)

        val youTubePlayerFragment = supportFragmentManager.findFragmentById(R.id.official_player_view) as YouTubePlayerSupportFragment?
        youTubePlayerFragment?.initialize("YOUR_API_KEY", this)
    }

    override fun onInitializationSuccess(provider: YouTubePlayer.Provider,youTubePlayer: YouTubePlayer,wasRestored: Boolean) {
        if (!wasRestored) {
            youTubePlayer.cueVideo("YE7VzlLtp-4")
        }
    }

    override fun onInitializationFailure(provider: YouTubePlayer.Provider,youTubeInitializationResult: YouTubeInitializationResult) {
        if (youTubeInitializationResult.isUserRecoverableError) {
            youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show()
        } else {
            val errorMessage = String.format(
                "There was an error initializing the YouTubePlayer (%1\$s)",
                youTubeInitializationResult.toString()
            )
            Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
        }
    }
}

At line 11 we have to replace YOUR_API_KEY with the API KEY we created before.

Run your project and see the results!

2nd Method (3rd Party Library Android YouTube Player)

Pros
  • Highly customizable
  • Gets updates
  • It’s the fastest from the other two methods
  • Doesn’t need an API KEY
  • Plays also copyrighted videos (e.g music videos)
  • Calculates the aspect ratio of the video automatically
Cons
  • Some devs have reported that their app has been rejected from the Google Play Store. (Never happened to me with my apps)

In this method, we’re going to use the 3rd party library Android YouTube Player, made by Pierfrancesco Soffritti, to embed our YouTube video into our app.

Add Android YouTube Player Library into our app

Let’s start by adding the library to build.gradle file:

dependencies {
    implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3'
}

Not let’s add our Youtube view to our layout like the following example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        tools:context=".AndroidYoutubePlayerActivity">

    <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
            android:id="@+id/third_party_player_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
</RelativeLayout>

Let’s go to our Kotlin class with the youtube view and add the following code:

class AndroidYoutubePlayerActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_android_youtube_player)

        third_party_player_view.getPlayerUiController().showFullscreenButton(true)
        third_party_player_view.addYouTubePlayerListener(object : AbstractYouTubePlayerListener() {
            override fun onReady(@NonNull youTubePlayer: YouTubePlayer) {
                val videoId = "YE7VzlLtp-4"
                youTubePlayer.cueVideo(videoId, 0f)
            }
        })

        third_party_player_view.getPlayerUiController().setFullScreenButtonClickListener(View.OnClickListener {
            if (third_party_player_view.isFullScreen()) {
                third_party_player_view.exitFullScreen()
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
                // Show ActionBar
                if (supportActionBar != null) {
                    supportActionBar!!.show()
                }
            } else {
                third_party_player_view.enterFullScreen()
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
                // Hide ActionBar
                if (supportActionBar != null) {
                    supportActionBar!!.hide()
                }
            }
        })
    }
}

As you see, in the lines 15-31 we have a listener for the full-screen button. When the user opens the video in full-screen mode, we hide the ActionBar and the StatusBar (available only for Android 4.1 and above) and we unhide them when closes it.

For more customization check out the documentation here.

.. and done!

3rd Method(WebView)

Pros
  • Very quick to setup
  • Doesn’t need an API KEY.
  • No need to install any library
Cons
  • Doesn’t play copyrighted videos (It says ‘Video unavailable’)
  • Poor performance
  • Zero customization
  • You have to calculate the aspect ratio of the video manually

Add YouTube Player with WebView into our app

First, let’s add a WebView into our layout like that:

<?xml version="1.0" encoding="utf-8"?>
<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"
        android:background="@color/colorPrimary"
        tools:context=".WebViewActivity">

    <WebView
            android:id="@+id/webview_player_view"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>

</RelativeLayout>

Now, in our Kotlin class let’s add the following code:

@SuppressLint("SetJavaScriptEnabled")
class WebViewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)


        webview_player_view.settings.javaScriptEnabled = true
        webview_player_view.loadUrl("https://www.youtube.com/embed/YE7VzlLtp-4")
    }
}

We need to have javascript enabled in our WebView to play embed YouTube videos.

Run it… and Voila!

You can find the final project here

Did you find this tutorial helpful?



If you have any questions, please feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments