Youtube Api Uploads Doesnt Show All Videos

This post was updated in January 2017.

The YouTube Android Histrion API enables you lot to contain video playback functionality into your Android applications. The API allows you to load and play YouTube videos (and playlists) and to customize and control the video playback experience.

You can load or cue videos into a actor view embedded in your application's UI. You can then control playback programmatically. For case play, pause, or seek to a specific bespeak in the loaded video. You lot can register event listeners to get callbacks for certain events, such as the role player loading a video or the player state changing. The API also has helper functionality to support orientation changes as well as transitions to fullscreen playback.

To get started, create a new project. I called mine VideoTube. On the next window of the Android Studio wizard you tin can exit the Minimum SDK version at the default API 15 (the YouTube API will only piece of work on API 10 and in a higher place). Select the Empty Activity template on the next window and MainActivity as the activity proper name on the last 1.

Before using the Android Youtube API, you need to register your application, including your digitally signed .apk file'due south public certificate in the Google Developers Panel. To register the awarding, follow these steps.

  1. Become to the Google Developers Console
  2. Create a new project. I named mine VideoTube.
  3. In the sidebar on the left, brand sure that Library is selected. On the right panel, select the Youtube Data API and Enable information technology on the page that follows.
  4. In the sidebar on the left, select Credentials. For credentials, the API supports OAuth 2.0, the use of an API key and of a Service business relationship. We'll use the API key option.
  5. Select API key from the Create Credentials dropdown bill of fare. A popup will appear with the value of your API central. Keep this window open, nosotros'll employ the primal in the next pace.

Note:

The popup window that displays the API primal has a Restrict Primal button that you tin use to restrict the key from unauthorised use. In this tutorial, nosotros won't restrict the key, but for an app that y'all programme to push to production, you should definitely restrict access to it. Key restriction lets yous specify which websites, IP addresses or apps can utilise this key. This tin assistance prevent unauthorised employ and quota theft.

Back in the Android app, create a grade named Config.java and paste in the following.

                      package            com.echessa.videotube            ;            /**  * Created past echessa on 1/xiii/17.  */            public            concluding            class            Config            {            individual            Config            (            )            {            }            public            static            terminal            String            YOUTUBE_API_KEY            =            "YOUR API KEY"            ;            }                  

Paste in your API key.

Download the latest version of the YouTube Android Actor API (1.ii.two at the time of writing). Unzip the downloaded file to find the library jar file and a sample application that you can utilize to meet what the library offers. The jar file is located in the libs folder. Re-create and paste it into your projection'south libs folder. To access the libs folder, utilise the Projection perspective on the Android Studio Project Explorer. Then aggrandize VideoTube -> app -> libs.

Project Explorer

Change back to the Android perspective, select the build.gradle (Module: app) file and add together the post-obit to the dependencies.

          compile            files            (            'libs/YouTubeAndroidPlayerApi.jar'            )                  

Sync the project'southward gradle files.

Add the following permission for internet admission to the AndroidManifest.xml file as a kid of the manifest tag and a sibling to the awarding.

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

Edit the strings.xml file every bit shown. These are all the string resource we'll crave.

                                                    <resource              >                                                      <string              proper name                              =                "app_name"                            >            VideoTube                              </string              >                                                      <cord              proper name                              =                "player_error"                            >            Error initializing YouTube player: %s                              </cord              >                                                      <cord              name                              =                "seek_to"                            >            Jump To                              </string              >                                                      <string              name                              =                "seek_to_hint"                            >            Seconds                              </string              >                                                      </resources              >                              

Next we'll add a YouTubePlayerView to the layout file. This view is used for displaying YouTube videos.

Modify activity_main.xml as shown.

                                                    <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"                                            tools:context                              =                ".MainActivity"                            >                                                      <com.google.android.youtube.player.YouTubePlayerView                              android:id                              =                "@+id/youtube_view"                                            android:layout_width                              =                "match_parent"                                            android:layout_height                              =                "wrap_content"                            />                                                      </RelativeLayout              >                              

We'll be using the YouTubePlayerView direct in our action as opposed to using the YouTubePlayerFragment. Because of this, the activity needs to extend the YouTubeBaseActivity course.

Modify MainActivity.java equally shown.

                      bundle            com.echessa.videotube            ;            import            android.content.                        Intent            ;            import            android.os.                        Bundle            ;            import            android.widget.                        Toast            ;            import            com.google.android.youtube.player.                        YouTubeBaseActivity            ;            import            com.google.android.youtube.player.                        YouTubeInitializationResult            ;            import            com.google.android.youtube.player.                        YouTubePlayer            ;            import            com.google.android.youtube.player.                        YouTubePlayer.Provider            ;            import            com.google.android.youtube.player.                        YouTubePlayerView            ;            public            grade            MainActivity            extends            YouTubeBaseActivity            implements            YouTubePlayer.OnInitializedListener            {            individual            static            last            int            RECOVERY_REQUEST            =            ane            ;            individual            YouTubePlayerView            youTubeView;            @Override            protected            void            onCreate            (            Parcel            savedInstanceState)            {            super            .            onCreate            (savedInstanceState)            ;            setContentView            (            R            .layout.activity_main)            ;            youTubeView            =            (            YouTubePlayerView            )            findViewById            (            R            .id.youtube_view)            ;            youTubeView.            initialize            (            Config            .YOUTUBE_API_KEY,            this            )            ;            }            @Override            public            void            onInitializationSuccess            (            Provider            provider,            YouTubePlayer            player,            boolean            wasRestored)            {            if            (            !wasRestored)            {            player.            cueVideo            (            "fhWaJi1Hsfo"            )            ;            // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo            }            }            @Override            public            void            onInitializationFailure            (            Provider            provider,            YouTubeInitializationResult            errorReason)            {            if            (errorReason.            isUserRecoverableError            (            )            )            {            errorReason.            getErrorDialog            (            this            ,            RECOVERY_REQUEST)            .            show            (            )            ;            }            else            {            String            fault            =            String            .            format            (            getString            (            R            .string.player_error)            ,            errorReason.            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 activity            getYouTubePlayerProvider            (            )            .            initialize            (            Config            .YOUTUBE_API_KEY,            this            )            ;            }            }            protected            Provider            getYouTubePlayerProvider            (            )            {            return            youTubeView;            }            }                  

In the above code, we created a class that is a subclass of YouTubeBaseActivity. This is required to brand use of YouTubePlayerView. We implemented YouTubePlayer.OnInitializedListener to heed for initialization success or failure. The interface has 2 methods, named onInitializationFailure() and onInitializationSuccess(). If initialization is successful, the cueVideo() method plays the YouTube video and incase of failure, checks to see whether the error is recoverable by user action.

If information technology's non then a Toast of the error is shown to the user and if it's user-recoverable, then the getErrorDialog() method shows a dialog that will enable the user to recover from the mistake.

For example, if the YouTube app isn't installed on the user'south device or is out of date, the dialog will have a prompt that upon confirmation, will open up the Google Play Store for the user to install or update it accordingly. If the YouTube app is disabled on the device, and then the prompt will open Organization Settings for the user to enable information technology.

When the user returns from the fault recovery dialog, onActivityResult() is called checks to meet if the user performed a recovery action. If so, we retry initialization.

Run the app and you should be able to play the video specified in the code.

Annotation:

You demand the YouTube app on your device for the video to play. The API client library interacts with a service that is distributed as part of the YouTube app for the Android platform. Users need to run version four.2.16 of the mobile YouTube app (or college) to use the API. Generally, devices running Android two.ii (Froyo) or later that have the Google Play Store app should be able to run the up-to-date version of the YouTube app.

YouTube Player

Responding to Playback Events and State Changes

In the app, yous might demand to have some action depending on the YouTube actor's events such as buffering, play, pause, seek and stop. Yous might want to testify the user a message or overlay the player view with another view once video playback stops or ends.

The YouTubePlayer has the following interface definitions to listen to such events:
YouTubePlayer.PlayerStateChangeListener – Interface definition for callbacks which invoked when the high level player state changes.
YouTubePlayer.PlaybackEventListener – Interface definition for callbacks which invoked when video playback events occur.
YouTubePlayer.OnFullscreenListener – Interface definition for callbacks which invoked when the histrion toggles between fullscreen on or off, either due to the user clicking the fullscreen button or a call to setFullscreen(boolean).
YouTubePlayer.PlaylistEventListener – Interface definition for callbacks which invoked when events related to playlists occur.

Nosotros'll look at the first two for this app.

Add the post-obit method to the MainActivity grade.

                      private            void            showMessage            (            Cord            bulletin)            {            Toast            .            makeText            (            this            ,            message,            Toast            .LENGTH_LONG)            .            show            (            )            ;            }                  

This volition create a Toast with the message passed into the function. This will save us from writing similar lines of code.

Side by side add the following 2 subclasses to the MainActivity class.

                      private            concluding            class            MyPlaybackEventListener            implements            YouTubePlayer.PlaybackEventListener            {            @Override            public            void            onPlaying            (            )            {            // Chosen when playback starts, either due to user action or call to play().            showMessage            (            "Playing"            )            ;            }            @Override            public            void            onPaused            (            )            {            // Called when playback is paused, either due to user action or call to interruption().            showMessage            (            "Paused"            )            ;            }            @Override            public            void            onStopped            (            )            {            // Called when playback stops for a reason other than being paused.            showMessage            (            "Stopped"            )            ;            }            @Override            public            void            onBuffering            (            boolean            b)            {            // Called when buffering starts or ends.            }            @Override            public            void            onSeekTo            (            int            i)            {            // Chosen when a leap in playback position occurs, either            // due to user scrubbing or telephone call to seekRelativeMillis() or seekToMillis()            }            }            individual            final            class            MyPlayerStateChangeListener            implements            YouTubePlayer.PlayerStateChangeListener            {            @Override            public            void            onLoading            (            )            {            // Called when the player is loading a video            // At this point, it'southward not set up to have commands affecting playback such as play() or break()            }            @Override            public            void            onLoaded            (            String            southward)            {            // Called when a video is done loading.            // Playback methods such as play(), intermission() or seekToMillis(int) may be called later this callback.            }            @Override            public            void            onAdStarted            (            )            {            // Called when playback of an advertisement starts.            }            @Override            public            void            onVideoStarted            (            )            {            // Called when playback of the video starts.            }            @Override            public            void            onVideoEnded            (            )            {            // Called when the video reaches its end.            }            @Override            public            void            onError            (            YouTubePlayer.ErrorReason            errorReason)            {            // Chosen when an error occurs.            }            }                  

The above creates classes that implement the YouTubePlayer.PlaybackEventListener and YouTubePlayer.PlayerStateChangeListener interfaces. For each course, I take implemented the interface methods and included a comment of when the callback is invoked. Y'all can take whatever activeness you desire in each callback. For our case, I accept included a Toast output for the onPlaying(), onPaused() and onStopped() methods that volition output a message when the effect happens.

Add the following class variables to the MainActivity file.

                      private            MyPlayerStateChangeListener            playerStateChangeListener;            private            MyPlaybackEventListener            playbackEventListener;                  

Add the post-obit to the bottom of onCreate() to initialize the above objects.

          playerStateChangeListener            =            new            MyPlayerStateChangeListener            (            )            ;            playbackEventListener            =            new            MyPlaybackEventListener            (            )            ;                  

Modify onInitializationSuccess() every bit shown. This sets the listeners on the YouTubePlayer object.

                      @Override            public            void            onInitializationSuccess            (            Provider            provider,            YouTubePlayer            player,            boolean            wasRestored)            {            role player.            setPlayerStateChangeListener            (playerStateChangeListener)            ;            histrion.            setPlaybackEventListener            (playbackEventListener)            ;            if            (            !wasRestored)            {            player.            cueVideo            (            "fhWaJi1Hsfo"            )            ;            // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo            }            }                  

Run the app and you lot should see different Toast messages appear when yous start playing the video, when y'all pause information technology and when it stops (for a reason other than existence paused, e.grand. the video ending or a playback error).

Custom Player Controls

The YouTube library does a good task of creating an out-of-the-box user friendly interface to play YouTube videos. As a developer, you might want to have this further and provide custom controls that will give the user more command over playback. For example, enable them to jump back and forth in the video, or enable them to play the next or previous video in a playlist.

We'll create a command in our app that will enable the user to jump to a specific time in the video.

The API provides two methods to jump playback:
seekToMillis() – Seeks to the specified time in the video.
seekRelativeMillis() – Seeks forward or backwards by the specified number of seconds.

We'll use the outset to leap to a specified fourth dimension in the video.

Modify activity_main.xml as shown.

                      <?xml version="1.0" encoding="utf-viii"?>                                          <LinearLayout                              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:orientation                              =                "vertical"                                            tools:context                              =                ".MainActivity"                            >                                                      <com.google.android.youtube.player.YouTubePlayerView                              android:id                              =                "@+id/youtube_view"                                            android:layout_width                              =                "match_parent"                                            android:layout_height                              =                "wrap_content"                            />                                                      <LinearLayout                              android:layout_width                              =                "match_parent"                                            android:layout_height                              =                "wrap_content"                            >                                                      <EditText                              android:id                              =                "@+id/seek_to_text"                                            android:layout_width                              =                "wrap_content"                                            android:layout_height                              =                "wrap_content"                                            android:inputType                              =                "number"                                            android:hint                              =                "@cord/seek_to_hint"                            />                                                      <Button                              android:id                              =                "@+id/seek_to_button"                                            android:text                              =                "@string/seek_to"                                            android:layout_width                              =                "wrap_content"                                            android:layout_height                              =                "wrap_content"                            />                                                      </LinearLayout              >                                                      </LinearLayout              >                              

In MainActivity add the post-obit course variable.

                      private            YouTubePlayer            player;                  

At the outset of onInitializationSuccess() gear up this variable.

                      this            .actor            =            player;                  

Add the post-obit to the bottom of onCreate().

                      final            EditText            seekToText            =            (            EditText            )            findViewById            (            R            .id.seek_to_text)            ;            Button            seekToButton            =            (            Push button            )            findViewById            (            R            .id.seek_to_button)            ;            seekToButton.            setOnClickListener            (            new            View.OnClickListener            (            )            {            @Override            public            void            onClick            (            View            5)            {            int            skipToSecs            =            Integer            .            valueOf            (seekToText.            getText            (            )            .            toString            (            )            )            ;            role player.            seekToMillis            (skipToSecs            *            1000            )            ;            }            }            )            ;                  

Run the app and you should be able to enter a number (in seconds) and have the video skip to that point. If you input a number that is larger than the duration of the video, and so the video volition skip to the end.

YouTube Player

Conclusion

In this tutorial, we have looked at how to embed a YouTube actor in your app. This is handy if you want your app users to be able to play YouTube videos while remaining in your app, instead of the YouTube app opening to play the video and so the user returning to your app afterwards playback.

The YouTube Android library provides a great API that enables you to customise this feel and we've just touched on its capabilities. To find out more near the library, exist sure to read through the documentation and the sample app that comes with the library download.

You can download the completed projection here. Recall to identify your key in the Config.java file.

I'd be keen to hear if you try the tutorial and your experiences and any questions you may take.

ensleyherhatiought51.blogspot.com

Source: https://www.sitepoint.com/using-the-youtube-api-to-embed-video-in-an-android-app/

0 Response to "Youtube Api Uploads Doesnt Show All Videos"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel