Play Youtube videos in your App

Gaurav Rajput
2 min readMay 23, 2020

--

Simple steps to be followed :

  1. Download youtube player API from https://developers.google.com/youtube/android/player/downloads
  2. Extract the downloaded file and copy “YouTubeAndroidPlayerApi.jar”
  3. Paste “YouTubeAndroidPlayerApi.jar” to your android project “libs” folder
  4. Register your application: open the credential page here https://console.developers.google.com/projectselector2/apis/credentials?supportedpurview=project&project&folder&organizationId
  5. Click on create Project (if you don't have already).

Giver your project name: Let's say “FirstProject” then click on “Create”

4. Click on Create Credential

5. Click on “API Key”

6. Your API key is created. Copy it and just click on “register API”

7. Paste this key. We will keep this API in the environment variable for safety. So paste it in “gradle.properties” file in your app like “YOUTUBE_DEVELOPER_KEY =your_key_goes_here”

8. In your app’s build.gradle file add YOUTUBE_DEVELOPER_KEY so that you can access it by typing `BuildConfig.YOUTUBE_DEVELOPER_KEY` anywhere in the app

android {
compileSdkVersion 29
defaultConfig {
applicationId "com.example.FirstProject"
minSdkVersion 16
targetSdkVersion 29
versionCode buildCode
versionName buildName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
buildConfigField 'String', 'YOUTUBE_DEVELOPER_KEY', YOUTUBE_DEVELOPER_KEY
}
}

9. Sync the Gradle

10. In your activity write a function and pass it videoId (given code is in Kotlin)

private fun startYoutubeActivity(videoId: String) {
val intent = YouTubeStandalonePlayer.createVideoIntent(this, BuildConfig.YOUTUBE_DEVELOPER_KEY, videoId)
if (intent.resolveActivity(this.packageManager) != null) {
this.startActivity(intent)
} else {
val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=$videoId"))
if (webIntent.resolveActivity(this.packageManager) != null) {
this.startActivity(webIntent)
} else {
// handle the error here
}
}
}

in this youtube URL “https://www.youtube.com/watch?v=kJQP7kiw5Fk” video id is “kJQP7kiw5Fk

11. Enjoy playing youtube videos in your app.

--

--