YouTube Integration Steps in Android

youtube-integration-android
Android / Android Application Development

YouTube Integration Steps in Android

There are mainly 3 steps to integrate youtube in your Android application.

1) Register Your Application in Google Developer Console

2) Add Dependency for YouTube

3) Android Integration Part

1) Register Your Application in Google Developer Console

  • Go to Google Developer Console

https://console.developers.google.com/projectselector/apis/dashboard

Login to Your Gmail account

After Login Create new Project in Google console

To Create a New Project Click on the Google Button, which redirects you to the following screen, now click to the +’ button of the right most corner of the screen.

Create a new project, here I am using YoutubeIntegration  as the project name

Click on Create button

  • Enable YouTube Data API Library

To enable YouTube Library, Go to the Sidebar On the Left, Select Library option then search library YouTube data API and then Enable it.

 

To generate API Key, Select a Credential option from the sidebar and select Create Credential button and choose an API key

 

then Select Restrict Key

 

Select Android App from Radio buttons and Click Add Package name and fingerprint.

Write Package name of your project like com.example.youtube(inside your Manifiest.xml file copy your package name)

To Generate SHA-1 Key,

Go to Your Android Project Click on Gradle which appears on the right side of the project, click Refresh button

Expand (YourProjectName)root Folder Task -> android -> (double Click on)signingReport and Click Save Buttons

 

Now, you have your SHA-1 key, Paste into the SHA-1 certificate fingerprint

Click Save button

 

2) Add Dependency for YouTube

compile files(‘libs/YouTubeAndroidPlayerApi.jar’)

Download the YouTubeAndroidPlayerApi.jar File from the following link

https://developers.google.com/youtube/android/player/downloads/

After downloading the .jar file, paste it into libs folder

3) Android Integration Part

AndroidManifiest.xml

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

activity_main.xml

<com.google.android.youtube.player.YouTubePlayerView
     android:id="@+id/youtube_view"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

MainActivity.Java

public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
    private static final int RECOVERY_REQUEST = 1;
    private YouTubePlayerView youTubeView;

 // You must extend the YouTubeBaseActivity otherwise it returns error unable to start activity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
        youTubeView.initialize(this.getString(R.string.youtube_api_key), this);
    }
 

// This method is called  when initialization of the player success 

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
        if (!b) {

 //  this method loads the video and play the specified video

// in our code we used the method extractVideoIdFromUrl(String URL) which finds the youtube id from the URL


 youTubePlayer.loadVideo(new YouTubeHelper().extractVideoIdFromUrl("https://www.youtube.com/watch?v=C4jiAzejpC8"));
          

}

}
 

// This method is called when initialization of the player fails


    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
        if (youTubeInitializationResult.isUserRecoverableError()) {
            youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
        } else {
            String error = String.format(getString(R.string.player_error), youTubeInitializationResult.toString());
            Toast.makeText(this, error, Toast.LENGTH_LONG).show();
        }
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOVERY_REQUEST) {
            // Retry initialization if user performed a recovery action
           getYouTubePlayerProvider().initialize(this.getString(R.string.youtube_api_key), this);
        }
    }
 

protected YouTubePlayer.Provider getYouTubePlayerProvider() {
        return youTubeView;
    }
}

YouTubeHelper.java

public class YouTubeHelper {
 
    final String youTubeUrlRegEx = "^(https?)?(://)?(www.)?(m.)?((youtube.com)|(youtu.be))/";
    final String[] videoIdRegex = { "\\?vi?=([^&]*)","watch\\?.*v=([^&]*)", "(?:embed|vi?)/([^/?]*)", "^([A-Za-z0-9\\-]*)"};
 


// using this method you can find out the youtube id from the url


    public String extractVideoIdFromUrl(String url) {
        String youTubeLinkWithoutProtocolAndDomain = youTubeLinkWithoutProtocolAndDomain(url);
 
        for(String regex : videoIdRegex) {
            Pattern compiledPattern = Pattern.compile(regex);
            Matcher matcher = compiledPattern.matcher(youTubeLinkWithoutProtocolAndDomain);
 
            if(matcher.find()){
                return matcher.group(1);
            }
        }
        return null;
    }
 
    private String youTubeLinkWithoutProtocolAndDomain(String url) {
        Pattern compiledPattern = Pattern.compile(youTubeUrlRegEx);
        Matcher matcher = compiledPattern.matcher(url);
 
        if(matcher.find()){
            return url.replace(matcher.group(), "");
        }
        return url;
    }
}

Output:

Thank you.

Happy Coding.

error:
×