How To Use Youtube Thumbnail Loader Android
android-youtube-player
android-youtube-actor is a stable and customizable open source YouTube player for Android. It provides a unproblematic View that can exist easily integrated in every Activity/Fragment.
The library is a wrapper over the IFrame Player API, which runs inside of a WebView. Therefore the YouTube app is not required on the user's device and at that place are no issues with YouTube Terms of Service.
The UI of the histrion is 100% customizable. The UI tin be completely replaced with a custom UI. However this should be done with cuation, as altering the UI of the IFrame role player might break YouTube'southward terms of service.
This library also provides a Chromecast YouTube player, that you can use to cast YouTube videos from your app to a Chromecast device.
Why does this library be?
The official library provided by Google to integrate YouTube videos in Android apps is the YouTube Android Actor API. Unfortunately this library is quite buggy (some bugs are 5+ years old) and has receive no updates in years. I personally found information technology quite unreliable and therefore impossible to use in production.
This, added to its limited options for customization and lack of Chromecast back up, atomic number 82 me to the evolution of this open source library.
A lengthier explanation to why yous may want to consider using an alternative to the official YouTube histrion is written in this Medium post.
A listing of published apps that are using this library: (allow me know if you want to add your app to this listing)
- reddit is fun
- Mobile Flick Database
- dingo
Does this library breaks YouTube terms of service?
TL;DR No.
The library uses YouTube's own web player to play videos. Therefore information technology is 100% compliant with terms of service. You tin can meet here how this is besides the official way of playing YouTube videos on iOS.
That said how you use the library matters, be sure to play videos just when the player is visible. If you follow the instructions in the documentation, the library volition automatically handle this for you lot.
Also call up when publishing your app on the PlayStore to write title and description in a way that makes information technology obvious that your app doesn't accept whatsoever affiliation with YouTube (the company). This is issue has nothing to do with the library itself, only I figured information technology may be useful knowledge for many of you because to use information technology.
Table of Contents (Core)
- Sample app
- Download
- Cadre
- Chromecast
- Quick start
- API documentation
- YouTubePlayerView
- XML attributes
- Initialization
- IFramePlayerOptions
- Full screen
- Release the YouTubePlayerView
- LifecycleObserver
- YouTubePlayer
- Get a reference to YouTubePlayer
- Load videos
- Utility for loading videos
- Events
- YouTubePlayerTracker
- YouTubePlayerListener
- onReady callback
- onStateChanged callback
- Create your own custom UI
- DefaultPlayerUiController
- Reusable UI components
- YouTubePlayerSeekBar
- FadeViewHelper
- TimeUtilities
- Network events
- Chromecast support
- Useful info
- Hardware dispatch
- Play YouTube videos in the background
- minSdk
- YouTubePlayerView
Table of Contents (Chromecast)
- Chromecast extension library
- Quick starting time and API documentation
- Download actress dependencies
- Sender
- Receiver
- Registration
- Hosting the Chromecast receiver
Sample app
- Get to source lawmaking of cadre sample app.
- Go to source lawmaking of chromecast-sender sample app.
- Download apk of core sample app.
- Download apk of chromecast-sender sample app.
Download
The Gradle dependency is bachelor via MavenCentral.
The minimum API level supported by this library is API 17.
Core
The core module contains the YouTube Actor. It'due south all y'all need to play YouTube videos in your app.
Add this to your module level build.gradle
file.
dependencies { implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:eleven.0.1' }
Chromecast
The chromecast-sender module contains the Chromecast YouTube Player. Employ information technology if you need to cast YouTube videos from your app to a Chromecast device.
Add this to your module level build.gradle
file.
dependencies { implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:0.26' }
Quick start
In order to starting time using the role player you demand to add a YouTubePlayerView to your layout.
<LinearLayout xmlns : android= "http://schemas.android.com/apk/res/android" xmlns : app= "http://schemas.android.com/apk/res-auto" android : layout_width= "match_parent" android : layout_height= "match_parent" android : orientation= "vertical" > <com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView android : id= "@+id/youtube_player_view" android : layout_width= "match_parent" android : layout_height= "wrap_content" app : videoId= "S0Q4gqBUs7c" app : autoPlay= "true" /> </LinearLayout>
It is recommended that you add YouTubePlayerView
as a lifecycle observer of its parent Activity/Fragment. You can read why in the documentation.
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view); getLifecycle().addObserver(youTubePlayerView);
(If y'all have problems adding YouTubePlayerView
every bit a LifecycleObserver
, yous probably aren't using androidx, I advise you lot migrate your dependencies)
This is all you lot need, a YouTube video is at present playing in your app.
If you want more command, everything can be washed programmatically by getting a reference to your YouTubePlayerView
and adding a YouTubePlayerListener
to it.
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view); getLifecycle().addObserver(youTubePlayerView); youTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { @ Override public void onReady(@ NonNull YouTubePlayer youTubePlayer) { String videoId = "S0Q4gqBUs7c"; youTubePlayer.loadVideo(videoId, 0); } });
If y'all decde to initialize the thespian programmatically, recollect to remove the autoPlay
and videoId
attributes from the YouTubePlayerView
in your XML file.
API documentation
The following sections provides detailed documentation for every component in the library.
If you lot see any problem or mistake in the documentation, feel free to contribute by opening an upshot an/or sending a pull request.
YouTubePlayerView
YouTubePlayerView
is the access point to the YouTubePlayer
.
You can add the View to your layout.
<LinearLayout xmlns : android= "http://schemas.android.com/apk/res/android" android : layout_width= "match_parent" android : layout_height= "match_parent" > <com.pierfrancescosoffritti.androidyoutubeplayer.cadre.actor.views.YouTubePlayerView android : id= "@+id/youtube_player_view" android : layout_width= "match_parent" android : layout_height= "wrap_content" /> </LinearLayout>
Or you can create it programmatically and manually add it to a ViewGroup.
YouTubePlayerView youTubePlayerView = new YouTubePlayerView(this); layout.addView(youTubePlayerView);
If the height of the View is set up to wrap_content
, the View volition automatically have an aspect ratio of 16:9, to match the attribute ratio of most YouTube videos.
XML attributes
If you add the view to your XML layout yous have the possibility to set a few custom attributes, to customize the view'due south look and behavior. Everything tin can also be washed programmatically.
- videoId
- autoPlay
- enableAutomaticInitialization
- handleNetworkEvents
videoId
This attribute expects a String
, which is the id of a YouTube video.
If set, the player will automatically first playing the video.
If non ready, the role player won't automatically play.
In general you should use this attribute if you lot want your player to play just ane video. This is not a rule, simply best practice. In fact, even if you lot set the aspect it is still possible to play other videos programmatically.
autoPlay
This attribute expects a boolean
. Its default value is false
.
If true
, the actor start playing the video provided with videoId
without waiting for user input.
If fake
, the role player will wait for user input before playing the video provided with videoId
.
If videoId
is not fix, this attribute is useless, therefore if it is set to true
YouTubePlayerView
volition throw an exception.
autoPlay
won't piece of work if YouTubePlayerView
is not added as a LifecycleObserver
of its parent Activeness/Fragment.
enableAutomaticInitialization
This aspect expects a boolean
. Its default value is true
.
If truthful
, YouTubePlayerView
will have care of its initialization.
If faux
, you volition have to initialize YouTubePlayerView
programmatically.
In general it makes sense to go out this attribute to true
. You may want to ready it to false
only if you need to initialize the view using IFramePlayerOptions
.
handleNetworkEvents
This aspect expects a boolean
. Its default value is true
.
If true
, YouTubePlayerView
handle network events by registering a NetworkReceiver
.
If false
, yous will be responsible for handling network events.
It is useful to have this attribute ready to true
so that if the connection drops while the player is initializing YouTubePlayerView
will exist able to resume the initialization automatically once the network is back.
If you determine to set up it to false
y'all should also disable enableAutomaticInitialization
and manage network events on your own.
Read more nigh network events here.
Initialization
If you need to initialize YouTubePlayerView
programmatically, you lot can set its xml attribute enableAutomaticInitialization
to fake. You can do the aforementioned programmatically by calling youTubePlayerView.setEnableAutomaticInitialization(faux)
.
Subsequently automatic initialization has been disabled, you need to have intendance of the initialization of YouTubePlayerView
.
You can utilize these methods:
YouTubePlayerView.initialize(YouTubePlayerListener listener)
YouTubePlayerView.initialize(YouTubePlayerListener listener, IFramePlayerOptions iframePlayerOptions)
YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents)
YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions)
initialize(YouTubePlayerListener)
Initialize the YouTubePlayer
. Network events are automatically handled past the thespian.
The statement is a YouTubePlayerListener
, you can read more virtually it here.
initialize(YouTubePlayerListener, boolean)
Initialize the YouTubePlayer
. By using the boolean
is possible to decide if the player should handle network events or not, read more than most network events here.
initialize(YouTubePlayerListener, boolean, IFramePlayerOptions)
By passing an IFramePlayerOptions
to the initialize method it is possible to ready some of the parameters of the IFrame YouTubePlayer. Read more nigh IFramePlayerOptions
hither.
All the possible parameters and values are listed hither. Non all of them are supported in this library because some don't make sense in this context. Open an issue if you lot need a parameter that is not currently supported.
IFramePlayerOptions
The IFramePlayerOptions
is an optional argument that can be passed to YouTubePlayerView.initialize(YouTubePlayerListener, boolean, IFramePlayerOptions)
, it can be used to set some of the parameters of the IFrame YouTubePlayer.
A simple example of how to use IFramePlayerOptions
tin exist found in the sample app here.
Use the Builder to go a IFramePlayerOptions
object.
IFramePlayerOptions iFramePlayerOptions = new IFramePlayerOptions.Architect() .controls(1) .build();
All the possible parameters and values are listed here. Not all of them are supported in this library because some don't brand sense in this context. Open an issue if you need a parameter that is non currently supported.
Supported options
controls
This option indicates whether the web-based UI of the IFrame actor should be hidden or visible.
If set to 0: web UI is not visible.
If set to 1: web UI is visible.
rel
This choice controls the related videos shown at the end of a video.
If set up to 0: related videos volition come from the same aqueduct as the video that was just played.
If set to one: related videos will come from multiple channels.
ivLoadPolicy
This option controls video annotations.
If set to 1: the player will show annotations.
If gear up to three: the actor won't show annotations.
ccLoadPolicy
This choice controls video captions. Information technology doesn't work with automatically generated captions.
If fix to 0: the player will show captions.
If set to 1: the histrion won't bear witness captions.
Total screen
You tin use the YouTubePlayerView
to enter and exit full-screen.
youTubePlayerView.enterFullScreen(); youTubePlayerView.exitFullScreen(); youTubePlayerView.isFullScreen(); youTubePlayerView.toggleFullScreen();
You tin also add listeners to get notified when the YouTubePlayerView
enters or exits full-screen.
youTubePlayerView.addFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener); youTubePlayerView.removeFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener);
Keep in mind that enterFullScreen()
and exitFullScreen()
will just ready YouTubePlayerView
's height and width to MATCH_PARENT
.
It is responsibility of the programmer to hide other Views in the Activeness, change the orientation of the Activity etc. The sample app contains an helper course that tin can help you to update your app state, only this is not part of the library.
If you need to change the orientation of your Action/Fragment, remember that by default Android recreates Activities and Fragments when the orientation changes. Make sure that you manually handle orientation changes by adding the attribute android:configChanges
to your Activity definition in the manifest.
<application > <activity android : configChanges= "orientation|screenSize|keyboardHidden|smallestScreenSize|screenLayout" /> </application>
Release the YouTubePlayerView
Think to release the YouTubePlayerView
when you're done using it, by calling YouTubePlayerView.release()
.
@ Override public void onDestroy() { super.onDestroy(); youTubePlayerView.release(); }
You don't need to manually release the role player if you lot registered it every bit an observer of your Activity/Fragment's lifecycle.
LifecycleObserver
YouTubePlayerView
implements the LifecycleObserver
interface, this means that it is a lifecycle aware component.
If added as an observer of your Activity/Fragment'due south lifecycle, YouTubePlayerView
will be smarter. It is highly recommended that you lot annals YouTubePlayerView
as a LifecycleObserver
.
lifecycleOwner.getLifecycle().addObserver(youTubePlayerView);
Adding YouTubePlayerView
as an observer to a lifecycle will allow YouTubePlayerView
to automatically pause the playback when the Activity/Fragment stops (not when it pauses, in social club to support multi-window applications).
If y'all desire your app to keep playing when the Action/Fragment is not visible (remember that this behavior is not immune, if y'all want to publish your app on the PlayStore), don't register the YouTubePlayerView
every bit a lifecycle observer. Just remember to manually call release()
when the Activity/Fragment is being destroyed.
YouTubePlayer
YouTubePlayer
is the component responsible for controlling the playback of YouTube videos. Y'all can come across its contract here.
Every YouTubePlayerView
contains a YouTubePlayer
.
Get a reference to YouTubePlayer
There are two ways to become a reference to the YouTubePlayer
, through the YouTubePlayerView
.
1. YouTubePlayerView.getYouTubePlayerWhenReady
YouTubePlayerView.getYouTubePlayerWhenReady
can be used to get a reference to the YouTubePlayer
. Every bit the name of the method says, you'll only become the thespian when it is ready.
Therefore this part takes a callback as statement, the callback will be called when the YouTubePlayer
is ready.
youTubePlayerView.getYouTubePlayerWhenReady(youTubePlayer -> { // do stuff with it })
two. YouTubePlayerListener
Every method of a YouTubePlayerListener
has the YouTubePlayer
as argument.
Load videos
To load a video y'all tin apply two methods.
YouTubePlayer.loadVideo(String videoId, float startTime)
or
YouTubePlayer.cueVideo(String videoId, bladder startTime)
The difference between the two is that loadVideo
loads and automatically plays the video, while cueVideo
just loads video and thumbnail but doesn't autoplay.
Utility for loading videos
If the Action/Fragment is in the groundwork, only you created a YouTubePlayerListener
that calls loadVideo
when onReady
is called, the video will start playing even if the Activity is in the background.
To solve this problem you should use the loadOrCueVideo
function.
Provided every bit an utility role in Java.
YouTubePlayerUtils.loadOrCueVideo( youTubePlayer, getLifecycle(), videoId, startTime );
And as an extension office in Kotlin.
youTubePlayer.loadOrCueVideo(lifeCycle, videoId, startTime)
This function will call loadVideo
just if the Activity is resumed, otherwise information technology will call cueVideo
, so that the video starts loading but not playing.
Events
During its existence the player volition constantly emit events, you can easily listen to all of them by adding a YouTubePlayerListener
to it.
YouTubePlayerTracker
YouTubePlayerTracker
is an utility provided by the library to hands keep rail of a YouTubePlayer
'south state and other information.
YouTubePlayerTracker
is a YouTubePlayerListener
, therefore in order to utilise it yous need to add it as a listener to the YouTubePlayer
.
You tin can then utilise the tracker to become the thespian's land and diverse information about the video that is being played.
YouTubePlayerTracker tracker = new YouTubePlayerTracker(); youTubePlayer.addListener(tracker); tracker.getState(); tracker.getCurrentSecond(); tracker.getVideoDuration(); tracker.getVideoId();
YouTubePlayerListener
A YouTubePlayerListener
is used to intercept events emitted by a YouTubePlayer
.
During its existence a YouTubePlayer
will constantly emit events, y'all can listen to them by calculation a YouTubePlayerListener
to it.
youTubePlayer.addListener(YouTubePlayerListener listener); youTubePlayer.removeListener(YouTubePlayerListener listener);
These are the method that a YouTubePlayerListener
must implement, every method takes a reference to the YouTubePlayer
and some other arguments.
// Called when the player is set up to play videos. // You should kickoff using the player simply subsequently this method is called. void onReady(@ NonNull YouTubePlayer youTubePlayer) // Called every time the land of the player changes. void onStateChange(@ NonNull YouTubePlayer youTubePlayer, @ NonNull PlayerConstants.PlayerState land) // Called every time the quality of the playback changes. void onPlaybackQualityChange(@ NonNull YouTubePlayer youTubePlayer, @ NonNull PlayerConstants.PlaybackQuality playbackQuality) // Called every time the speed of the playback changes. void onPlaybackRateChange(@ NonNull YouTubePlayer youTubePlayer, @ NonNull PlayerConstants.PlaybackRate playbackRate) // Called when an error occurs in the player. void onError(@ NonNull YouTubePlayer youTubePlayer, @ NonNull PlayerConstants.PlayerError fault) // Called periodically by the histrion, the argument is the number of seconds that take been played. void onCurrentSecond(@ NonNull YouTubePlayer youTubePlayer, float second) // Chosen when the total duration of the video is loaded. // Notation that getDuration() will render 0 until the video's metadata is loaded, which unremarkably happens only after the video starts playing. void onVideoDuration(@ NonNull YouTubePlayer youTubePlayer, float duration) // Called periodically by the actor, the statement is the per centum of the video that has been buffered. void onVideoLoadedFraction(@ NonNull YouTubePlayer youTubePlayer, float loadedFraction) // Called when the id of the current video is loaded void onVideoId(@ NonNull YouTubePlayer youTubePlayer, Cord videoId) void onApiChange(@ NonNull YouTubePlayer youTubePlayer)
If you don't desire to implement all the methods of this interface, y'all can extend AbstractYouTubePlayerListener
instead of implementing YouTubePlayerListener
and override only the methods you are interested in.
For more information on the methods defined in the YouTubePlayerListener
interface, please refer to the documentation divers above each method in the codebase.
onReady callback
The onReady callback of a YouTubePlayerListener
is chosen once, when the YouTubePlayer
is ready to be used for the commencement fourth dimension. You can't use a YouTubePlayer
earlier it is ready.
onStateChanged callback
The YouTubePlayer
has a state, that changes accordingly to the playback changes. The list of possible states is the same of the YouTube IFrame Player API.
UNKNOWN UNSTARTED Ended PLAYING PAUSED BUFFERING VIDEO_CUED
Create your own custom UI
Customization is an important aspect of this library. If need to, you can completely supersede the default UI of the player.
YouTubePlayerView
has methods for that.
View inflateCustomPlayerUi(@ LayoutRes int customUiLayoutID) void setCustomPlayerUi(View view)
This method takes in the id
of a layout resource, which is a regular XML file containing the definition of a layout, or a View
.
The new UI will be overlayed over the player. For this reason information technology is recommended to disable the UI of the IFrame player, by initializing the YouTubePlayerView
with IFramePlayerOptions
.
// disable web ui IFramePlayerOptions options = new IFramePlayerOptions.Builder().controls(0).build(); youTubePlayerView.initialize(listener, options);
You are responsible for managing your custom UI with your own code. Meaning: you should write your own form to manage the UI. A unproblematic simply consummate example can be seen here, in the sample app, I recommend taking a few minutes to read it, it should exist niggling to empathise.
Case (taken from sample app):
View customPlayerUi = youTubePlayerView.inflateCustomPlayerUi(R.layout.custom_player_ui); YouTubePlayerListener listener = new AbstractYouTubePlayerListener() { @ Override public void onReady(@ NonNull YouTubePlayer youTubePlayer) { CustomPlayerUiController customPlayerUiController = new CustomPlayerUiController(CustomUiActivity.this, customPlayerUi, youTubePlayer, youTubePlayerView); youTubePlayer.addListener(customPlayerUiController); youTubePlayerView.addFullScreenListener(customPlayerUiController); YouTubePlayerUtils.loadOrCueVideo( youTubePlayer, getLifecycle(), VideoIdsProvider.getNextVideoId(),0f ); } }; // disable iframe ui IFramePlayerOptions options = new IFramePlayerOptions.Builder().controls(0).build(); youTubePlayerView.initialize(listener, options);
A blog post going deeper on this is bachelor at this link.
Example of a custom UI: (this is merely a ugly example, only here your design skills are the limit :))
Alert: when replacing the IFrame UI, exist carfeul not to break YouTube'south terms of service. Altering the player look and feel might be an issue if you intend to publish your app on the PlayStore.
DefaultPlayerUiController
DefaultPlayerUiController
is a pre-made custom UI available in the library. You can utilise it like this:
YouTubePlayerListener listener = new AbstractYouTubePlayerListener() { @ Override public void onReady(@ NonNull YouTubePlayer youTubePlayer) { // using pre-made custom ui DefaultPlayerUiController defaultPlayerUiController = new DefaultPlayerUiController(youTubePlayerView, youTubePlayer); youTubePlayerView.setCustomPlayerUi(defaultPlayerUiController.getRootView()); } }; // disable iframe ui IFramePlayerOptions options = new IFramePlayerOptions.Builder().controls(0).build(); youTubePlayerView.initialize(listener, options);
The UI will look something like this.
You can use the DefaultPlayerUiController
to hide views, add new view etc.
Menu
DefaultPlayerUiController
has an optional bill of fare. You lot tin can use these methods to control the menu'southward behavior:
PlayerUiController.showMenuButton(boolean prove); PlayerUiController.setMenuButtonClickListener(@ NonNull View.OnClickListener customMenuButtonClickListener);
By default the carte icon is not visible.
The default OnClickListener
opens the carte when the menu icon is clicked. You lot can change this behavior, for case to open a menu with a different UX, similar a bottom sheet panel. Evidently if you want a UX different from the one provided by the library, you are responsible for creating your ain components.
Carte du jour screenshot:
YouTubePlayerMenu
You can become a reference of the YouTubePlayerMenu
from the PlayerUiController
.
YouTubePlayerMenu PlayerUiController.getMenu()
One time you get a YouTubePlayerMenu
object y'all can add and remove items to it, show it and dismiss it.
YouTubePlayerMenu addItem(MenuItem menuItem) YouTubePlayerMenu removeItem(MenuItem menuItem) YouTubePlayerMenu removeItem(int itemIndex) void evidence(View anchorView) void dismiss()
Initially the YouTubePlayerMenu
doesn't contain whatever particular. You need to add together them.
MenuItem
MenuItem
s are the items of the YouTubePlayerMenu
. They have a title, an optional icon and a OnClickListener
that is chosen when the detail is clicked.
Reusable UI components
The library provides some pre-built UI components, these components are useful to reduce the time needed to build your own UI and controllers.
YouTubePlayerSeekBar
This component is useful to display and control the time of the playback. It shows the electric current time, the full elapsing of the video and a seek bar.
You tin can add it to your layout programmatically or in your xml.
<com.pierfrancescosoffritti.androidyoutubeplayer.cadre.ui.views.YouTubePlayerSeekBar android : id= "@+id/youtube_player_seekbar" android : layout_width= "match_parent" android : layout_height= "wrap_content" app : fontSize= "12sp" app : color= "@color/red" />
It is possible to alter font size and color by using the fontSize
and colour
attributes.
YouTubePlayerSeekBar
implements YouTubePlayerListener
. In order for it to work you demand to add it as a listener to your YouTubePlayer
object.
youTubePlayer.addListener(youTubePlayerSeekBar);
You lot may wan to heed to events from YouTubePlayerSeekBar
, in order to update the electric current time of your YouTubePlayer
when the user moves the touch bar. To do that laissez passer a YouTubePlayerSeekBarListener
to YouTubePlayerSeekBar
.
youTubePlayerSeekBar.setYoutubePlayerSeekBarListener(new YouTubePlayerSeekBarListener() { @ Override public void seekTo(float time) { youTubePlayer.seekTo(time); } });
FadeViewHelper
An helper class that automatically fades out a view when not used. It tin be used to automate the fade in and out of a container for the thespian controls, so that they automatically fade when appropriate.
The FadingFrameLayout
is a YouTubePlayerListener
therefore information technology can change it's behavior based on the state of the player. For instance: if the video is paused it won't automatically fade out.
You tin can initialize information technology by passing to the constructor the view you lot want to be fading.
FadeViewHelper fadeViewHelper = new FadeViewHelper(controlsContainer);
It is possible to alter the blitheness elapsing and fade out filibuster by using the setter methods.
fadeViewHelper.setAnimationDuration(FadeViewHelper.DEFAULT_ANIMATION_DURATION); fadeViewHelper.setFadeOutDelay(FadeViewHelper.DEFAULT_FADE_OUT_DELAY);
They both take the fourth dimension in milliseconds.
In order for FadeViewHelper
to work properly you need to add information technology as a listener to your YouTubePlayer
object.
youTubePlayer.addListener(fadeViewHelper);
Apply the method FadeViewHelper.setDisabled(boolean)
to disable the automatic fading.
Use the method FadeViewHelper.toggleVisibility()
to toggle the visibility of the target view, with a fade animation.
TimeUtilities
A fix of utilities than can be used to format time Strings (like elapsing and electric current time of videos).
String TimeUtilities.formatTime(float timeInSeconds)
Takes in the time in seconds and returns a Cord with the time formatted as "M:SS". (One thousand = minutes, S = seconds).
Network events
YouTubePlayerView
automatically handles network events, using an internal BroadcastReceiver. Y'all can choose to enable or disable this feature when initializing the player, or by setting the xml attribute app:handleNetworkEvents="imitation"
.
Using the internal BroadcastReceiver is the easiest and recommended way to handle network events. The library is capable of handling cases in which the connexion goes off and the playback can't continue, or cases in which the connection goes off while the player is in the procedure of initialization.
If you want to use your ain BroadcastReceiver make certain to comprehend all the possible scenarios, in order to provide a good user experience.
Chromecast support
If you need to cast YouTube videos to a Chromecast device you lot can use the chromecast-sender extension library. Read its documentation hither.
Useful info
Hardware dispatch
Is important that the Activity containing the YouTubePlayerView is hardware accelerated. This selection is enabled by default, yous don't have to modify anything in your app. Unless you manually disabled hardware acceleration.
If y'all demand to disable hardware acceleration in your awarding, you tin enable it at the Action level, simply for the Activeness containing the YouTubePlayerView
, as explained here.
Disabling hardware dispatch on the Action containing YouTubePlayerView
may outcome in some weird beliefs. The one I accept observed so far shows a blackness image in the actor, while the audio is playing commonly.
Play YouTube videos in the groundwork
With this library it's piece of cake to play YouTube videos when the app is not visible. In order to practise that you only accept to non telephone call youTubePlayer.pause()
when the Activity is being paused or stopped and enable background playback by calling YouTubePlayerView.enableBackgroundPlayback(true)
.
Adding YouTubePlayerView
every bit an observer to a lifecycle volition automatically cause the role player to break the playback when the Action/Fragment stops.
Therefore if you want your app to keep playing even when the Activity/Fragment is paused/stopped, don't annals information technology as a lifecycle observer and enable background playback for the view. Merely remember to manually call YouTubePlayerView.release()
when the Activeness/Fragment is destroyed.
Remember that this behavior is against YouTube terms of service, therefore if y'all decide to let background playback you won't be able to publish your app on the Play Store.
Employ this functionality but if you plan to build the app for personal use or if you plan to distribute information technology through different channels.
minSdk
The minSdk of the library is 17. At this point in time it doesn't make much sense for new apps to support older versions of Android.
I'm not sure how WebView will carry on older versions of Android, but technically it should be possible to lower the minSdk. If you absolutely demand to support older devices, I advise you lot fork the library and lower the minSdk yourself.
Chromecast extension library
The chromecast-sender extension library extends the core library with chromecast functionalities. It shares some interfaces with the core library, therefore they tin can be used together.
The telescopic of this library is to provide the basic framework and utilities needed to bandage YouTube videos to a Chromecast device.
The api of this library is non 100% finalized yet, but is stable. You tin use it in your apps.
Quick starting time - Chromecast
A Google Cast awarding is made of two components: a Sender and a Receiver.
- Sender: is responsible for initiating the cast sessions. In our case the sender is an Android app.
- Receiver: a web app that gets downloaded on the Chromecast when a sender initiates a cast sessions.
Download actress dependencies
To use Google Cast functionalities add together the chromecast-sender module to your dependencies:
final-version.
implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:last-version' // this is not needed to apply the library, but it provides the quite useful cast push button. implementation 'androidx.mediarouter:mediarouter:last-version'
Sender
In order to utilize the Google Bandage framework an app has to declare a OptionsProvider
, as described in the Google Cast documentation.
Add together this class to your project:
public final class CastOptionsProvider implements com.google.android.gms.cast.framework.OptionsProvider { public com.google.android.gms.cast.framework.CastOptions getCastOptions(Context appContext) { // Register you custom receiver on the Google Cast SDK Developer Console to get this ID. String receiverId = ""; return new com.google.android.gms.cast.framework.CastOptions.Architect() .setReceiverApplicationId(receiverId) .build(); } public Listing<SessionProvider> getAdditionalSessionProviders(Context context) { return null; } }
You lot tin can read how to become a receiverId
here.
Add the OptionsProvider
to your manifest.xml
file.
(OPTIONS_PROVIDER_CLASS_NAME
is meant to be like that, change only the android:value
aspect)
<meta-information android : name= "com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME" android : value= "yourpackagename.CastOptionsProvider" />
Add a MediaRouterButton to your layout, in your xml file or programmatically.
<LinearLayout xmlns : android= "http://schemas.android.com/apk/res/android" android : id= "@+id/root" android : layout_width= "match_parent" android : layout_height= "match_parent" android : orientation= "vertical" > <androidx.mediarouter.app.MediaRouteButton android : id= "@+id/media_route_button" android : layout_width= "wrap_content" android : layout_height= "wrap_content" /> </LinearLayout>
Then in your Activity/Fragment get a reference to the MediaRouteButton
and check the status of the GooglePlayServices on the user'due south phone.
individual int googlePlayServicesAvailabilityRequestCode = i; @ Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); androidx.mediarouter.app.MediaRouteButton mediaRouteButton = findViewById(R.id.media_route_button); CastButtonFactory.setUpMediaRouteButton(this, mediaRouteButton); // can't use CastContext until I'm sure the user has GooglePlayServices PlayServicesUtils.checkGooglePlayServicesAvailability(this, googlePlayServicesAvailabilityRequestCode, this::initChromecast); } @ Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // can't employ CastContext until I'k sure the user has GooglePlayServices if(requestCode == googlePlayServicesAvailabilityRequestCode) PlayServicesUtils.checkGooglePlayServicesAvailability(this, googlePlayServicesAvailabilityRequestCode, this::initChromecast); } private void initChromecast() { new ChromecastYouTubePlayerContext( CastContext.getSharedInstance(this).getSessionManager(), new SimpleChromecastConnectionListener() ); }
You can easily bank check the GooglePlayServices status past using PlayServicesUtils.checkGooglePlayServicesAvailability
, a utility function provided past the chromecast-sender library.
PlayServicesUtils.checkGooglePlayServicesAvailability
does what is described here, in the official doctor. It will check the status of GooglePlayServices and will bear witness a dialog to the user if some activity is needed in guild to prepare the problem. Information technology won't brandish anything if everything is ok (which information technology is, 99% of the cases), in this case it will only telephone call the function passed as 3rd parameter. If there are some problems, the result of the operation is delivered through the onActivityResult
callback.
Once yous're sure the user's GooglePlayServices is all right, you can create the ChromecastYouTubePlayerContext
. The access point to the chromecast-sender library.
ChromecastYouTubePlayerContext
is the entry betoken to the chromecast-sender library. One time it is created, it automatically starts listening for Chromecast connexion events. The ChromecastConnectionListener
passed to the constructor will be used to practise just that.
When a user clicks the MediaRouteButton
a serial of events will be triggered in the framework, use ChromecastConnectionListener
's callbacks to be notified of these events.
individual class SimpleChromecastConnectionListener implements ChromecastConnectionListener { @ Override public void onChromecastConnecting() { Log.d(getClass().getSimpleName(), "onChromecastConnecting"); } @ Override public void onChromecastConnected(@ NonNull ChromecastYouTubePlayerContext chromecastYouTubePlayerContext) { Log.d(getClass().getSimpleName(), "onChromecastConnected"); initializeCastPlayer(chromecastYouTubePlayerContext); } @ Override public void onChromecastDisconnected() { Log.d(getClass().getSimpleName(), "onChromecastDisconnected"); } private void initializeCastPlayer(ChromecastYouTubePlayerContext chromecastYouTubePlayerContext) { chromecastYouTubePlayerContext.initialize(new AbstractYouTubePlayerListener() { @ Override public void onReady(@ NonNull YouTubePlayer youTubePlayer) { youTubePlayer.loadVideo("S0Q4gqBUs7c", 0f); } }); } }
Only after a Chromecast connection has been established you tin initialize the ChromecastConnectionListener
.
From now on it will be the same every bit using a local YouTubePlayer
. As yous tin see in the instance, yous demand to phone call ChromecastYouTubePlayerContext.initialize
, providing a YouTubePlayerListener
.
The YouTubePlayerListener
will notify you of changes in the playback. You lot can call loadVideo
, cueVideo
, pause
, play
etc.. on the YouTubePlayer
object as you lot're used to, the library will take care of the communication with the Google Cast device.
For how to use the YouTubePlayer
object and YouTubePlayerListener
, y'all can refer to the documentation for the cadre library, YouTubePlayer.
This example can be found in the chromecast-sender sample app, written in Kotlin and in the core sample app, written in Java.
Screenshot of the CastButton added to the YouTubePlayerView:
Receiver
This library requires a custom receiver, you tin find the source code of the chromecast-receiver here.
Yous don't demand to change annihilation here, it merely works. Take this code and upload it (every bit it is) on your server. (Read the hosting paragraph to learn more about hosting).
Registration
In order to use your receiver you need a receiverId. This is the ID of your receiver app. To get a receiver ID y'all demand to register your receiver on the Google Cast SDK developer console, y'all can larn how to exercise it past reading the official documentation. Think to register a Custom Receiver, this is the type of receiver y'all need for this library.
Hosting the chromecast-receiver
Yous will be required to host your receiver somewhere, host it where you lot adopt. Firebase free hosting may exist a expert option, for evolution.
For any question feel free to open an issue on the GitHub repository.
Source: https://github.com/PierfrancescoSoffritti/android-youtube-player
Posted by: rinknottionged.blogspot.com
0 Response to "How To Use Youtube Thumbnail Loader Android"
Post a Comment