Saturday, July 11, 2020

Add YouTube Video Player in Android App

How to Add Youtube Video in Android App


In our Android App we can easily add a youtube video link in our Android App.

For this we need to following things;

Step 1 : Create an API key

  1. You must  create an API key on https://console.developers.google.com/
  2. Go to the link
  3. Click on Credentials in Left Pane
  4. Click on "Create Credentials"


You need to enter your app package name and SHA Key, Click Save
Your API key will be created

See the Screenshot below.





Step 2 :  Add YouTubePlayerView in layout


<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical
"        android:background="#006080">

  
        <com.google.android.youtube.player.YouTubePlayerView 
           android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible"
            android:layout_gravity="center_horizontal"
            android:id="@+id/youtube_player"      />


    </LinearLayout>


Loading Video in Activity


public class PlayYouTubeVideoActivity extends YouTubeBaseActivity
{

    YouTubePlayerView youTubePlayerView;
 
    YouTubePlayer.OnInitializedListener onInitializedListener;


    @Override    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.watchvideo);

        youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
      
        onInitializedListener = new YouTubePlayer.OnInitializedListener(){
            @Override            
             public void onInitializationSuccess(YouTubePlayer.Provider provider,
                                               
             YouTubePlayer youTubePlayer, boolean b) {

                youTubePlayer.loadVideo("XXXXXXX");//Enter your Youtube Video ID here
                youTubePlayer.play();
            }

            @Override           
           public void onInitializationFailure(YouTubePlayer.Provider provider, 
             YouTubeInitializationResult youTubeInitializationResult) {
                Log.i("KAMLESH","Youtube not initialized 
             "+youTubeInitializationResult.getErrorDialog(PlayYouTubeVideoActivity.this,5));
            }
        };

        youTubePlayerView.initialize("ENTER YOUR API KEY HERE",onInitializedListener);


    }

}



Screenshot




No comments:

Post a Comment