### Load Video with Start Time Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Loads a YouTube video and starts playing it immediately. Specify the video ID and an optional start time in seconds. ```java YouTubePlayer.loadVideo(String videoId, float startTime) ``` -------------------------------- ### Cue Video with Start Time Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Loads a YouTube video and its thumbnail but does not autoplay. Specify the video ID and an optional start time in seconds. ```java YouTubePlayer.cueVideo(String videoId, float startTime) ``` -------------------------------- ### Initialize Player with Custom UI and Listener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md This example demonstrates inflating a custom UI, setting up a listener, and initializing the player with disabled controls. It also shows how to load a video using YouTubePlayerUtils. ```java 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); YouTubePlayerUtils.loadOrCueVideo( youTubePlayer, getLifecycle(), VideoIdsProvider.getNextVideoId(),0f ); } }; // disable iframe ui IFramePlayerOptions options = new IFramePlayerOptions.Builder(context).controls(0).build(); youTubePlayerView.initialize(listener, options); ``` -------------------------------- ### Cue Video by ID Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Prepares a video to play by its YouTube ID and optionally sets a start time, without automatically starting playback. Sends the video ID to the bridge. ```javascript function cueVideo(videoId, startSeconds) { player.cueVideoById(videoId, startSeconds); YouTubePlayerBridge.sendVideoId(videoId); } ``` -------------------------------- ### Get YouTubePlayer Reference Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Use this method to get a reference to the YouTubePlayer when it's ready. A callback is provided to handle the player instance. ```java youTubePlayerView.getYouTubePlayerWhenReady(youTubePlayer -> { // do stuff with it }) ``` -------------------------------- ### Initialize YouTubePlayer with DefaultPlayerUiController Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initialize the YouTubePlayerView and set the DefaultPlayerUiController's root view as the custom player UI. This example also shows how to disable the default iframe controls. ```java 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(context).controls(0).build(); youTubePlayerView.initialize(listener, options); ``` -------------------------------- ### Initialize Ad Blocking Logic Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Call this function from `sendPlayerStateChange` to start the ad blocking mechanism. It sets up an interval to periodically check for and attempt to skip ads. ```javascript let adblockIntervalId; function initializeAdBlock() { if (adblockIntervalId) { clearInterval(adblockIntervalId); } const playerIFrame = document.querySelector("iframe"); if (playerIFrame) { adblockIntervalId = setInterval(() => { if (!playerIFrame) { return; } const frameDoc = playerIFrame.contentDocument; if (!frameDoc) { return; } const adsContainer = frameDoc.querySelector('.video-ads'); if (!adsContainer || adsContainer.childElementCount == 0) { return; } const adsVideo = adsContainer.querySelector("video"); if (adsVideo) { adsVideo.muted = true; adsVideo.style.display = 'none'; adsVideo.currentTime = adsVideo.duration - 0.15; adsVideo.muted = false; adsVideo.style.display = ''; if (adblockIntervalId) { clearInterval(adblockIntervalId); } } else { const isAdShowing = frameDoc.getElementsByClassName('ad-showing').length != 0; if (!isAdShowing) { return; } const mainVideo = frameDoc.querySelector('.html5-main-video'); if (!mainVideo) { return; } mainVideo.muted = true; mainVideo.currentTime = mainVideo.duration - 0.15; mainVideo.muted = false; if (adblockIntervalId) { clearInterval(adblockIntervalId); } } }, 100); } } ``` -------------------------------- ### Initialize MediaRouteButton and Chromecast Context Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md In your Activity, get a reference to the MediaRouteButton and use CastButtonFactory to set it up. Check for Google Play Services availability before initializing the ChromecastYouTubePlayerContext. ```java private int googlePlayServicesAvailabilityRequestCode = 1; @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 use CastContext until I'm 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() ); } ``` -------------------------------- ### Create IFramePlayerOptions with Builder Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Instantiate `IFramePlayerOptions` using its Builder to configure IFrame YouTubePlayer parameters such as controls, related videos, annotations, captions, start, and end times. ```java IFramePlayerOptions iFramePlayerOptions = new IFramePlayerOptions.Builder(context) .controls(1) .build(); ``` -------------------------------- ### Get YouTubePlayerMenu Instance Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Menu Retrieve the YouTubePlayerMenu instance from the PlayerUIController to interact with the menu. ```Java PlayerUIController.getMenu(); ``` -------------------------------- ### Programmatic Video Loading Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Programmatically load a YouTube video by getting a reference to the YouTubePlayerView, adding a listener, and calling loadVideo in the onReady callback. ```java 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); } }); ``` -------------------------------- ### Get PlayerUIController Reference Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Obtain a reference to the PlayerUIController from the YouTubePlayerView to manage UI elements. ```java youtubePlayerView.getPlayerUIController(); ``` -------------------------------- ### Get YouTubePlayerMenu Reference Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Retrieve the YouTubePlayerMenu object from the PlayerUiController to manage menu items. ```java YouTubePlayerMenu PlayerUiController.getMenu() ``` -------------------------------- ### Get Player UI Controller Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Retrieve the PlayerUIController from the YouTubePlayerView to interact with the player's user interface elements. ```java PlayerUIController YouTubePlayerView.getPlayerUIController(); ``` -------------------------------- ### Load Video by ID Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Loads a new video into the player using its YouTube ID and optionally starts playback from a specific time. Also sends the video ID to the bridge. ```javascript function loadVideo(videoId, startSeconds) { player.loadVideoById(videoId, startSeconds); YouTubePlayerBridge.sendVideoId(videoId); } ``` -------------------------------- ### YouTubePlayerTracker Usage Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayer Add a YouTubePlayerTracker to listen for player events and track its state. Use the tracker to get the current playback state, time, video duration, and video ID. ```java YouTubePlayerTracker tracker = new YouTubePlayerTracker(); youtubePlayer.addListener(tracker); tracker.getState(); tracker.getCurrentSecond(); tracker.getVideoDuration(); tracker.getVideoId(); ``` -------------------------------- ### YouTube Player Initialization and Event Handling Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html This snippet initializes the YouTube player with specified configurations and event listeners. It's crucial for setting up the player and receiving playback events. ```javascript var UNSTARTED = "UNSTARTED"; var ENDED = "ENDED"; var PLAYING = "PLAYING"; var PAUSED = "PAUSED"; var BUFFERING = "BUFFERING"; var CUED = "CUED"; var YouTubePlayerBridge = window.YouTubePlayerBridge; var YouTubePlayerCallbacks = window.YouTubePlayerCallbacks; var player; var timerId; function onYouTubeIframeAPIReady() { YouTubePlayerBridge.sendYouTubeIFrameAPIReady(); var youtubePlayerConfig = { height: '100%', width: '100%', events: { onReady: function(event) { YouTubePlayerBridge.sendReady() }, onStateChange: function(event) { sendPlayerStateChange(event.data) }, onPlaybackQualityChange: function(event) { YouTubePlayerBridge.sendPlaybackQualityChange(event.data) }, onPlaybackRateChange: function(event) { YouTubePlayerBridge.sendPlaybackRateChange(event.data) }, onError: function(error) { YouTubePlayerBridge.sendError(error.data) }, onApiChange: function(event) { YouTubePlayerBridge.sendApiChange() } }, playerVars: <> }; if (<>) { youtubePlayerConfig.videoId = <>; } player = new YT.Player('youTubePlayerDOM', youtubePlayerConfig); } ``` -------------------------------- ### Initialize YouTubePlayer Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Initialize the YouTubePlayer by calling the initialize method with a listener and a flag for network event handling. The onInitSuccess callback provides the YouTubePlayer instance. ```java YouTubePlayerView.initialize(YouTubePlayerInitListener listener, boolean handleNetworkEvents); ``` -------------------------------- ### Initialize Player for Playlists Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Configure IFramePlayerOptions to play a YouTube playlist by specifying the list type and playlist ID. ```kotlin val iFramePlayerOptions = IFramePlayerOptions.Builder(context) .controls(1) .listType("playlist") .list(PLAYLIST_ID) .build() ``` -------------------------------- ### Initialize FadeViewHelper Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Create an instance of FadeViewHelper, passing the container view for your player controls to its constructor. ```java FadeViewHelper fadeViewHelper = new FadeViewHelper(controlsContainer); ``` -------------------------------- ### Initialize YouTubePlayerView Programmatically Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Create a YouTubePlayerView instance in code and add it to a ViewGroup. This is an alternative to adding it via XML. ```java YouTubePlayerView youTubePlayerView = new YouTubePlayerView(this); layout.addView(youTubePlayerView); ``` -------------------------------- ### Get Mute Status Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Retrieves the current mute status of the player and sends the boolean value back via a callback. ```javascript function getMuteValue(requestId) { var isMuted = player.isMuted(); YouTubePlayerCallbacks.sendBooleanValue(requestId, isMuted); } ``` -------------------------------- ### Enable Live Video UI Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Call this method to configure the player's UI for live video playback. The developer must manually enable this, as the player cannot detect live streams automatically. ```java PlayerUIController.enableLiveVideoUI(boolean enable); ``` -------------------------------- ### Implement YouTube Login with WebView Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Use this Java code to create a WebView, enable necessary settings for login, and load the YouTube login URL. The WebViewClient is configured to detect successful login by checking redirects to YouTube domains. ```java private void log_in() { WebView webView = new WebView(context); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setSavePassword(true); webView.getSettings().setSaveFormData(true); webView.loadUrl("https://accounts.google.com/ServiceLogin?service=youtube&uilel=3&passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Faction_handle_signin%3Dtrue%26app%3Dm%26hl%3Dtr%26next%3Dhttps%253A%252F%252Fm.youtube.com%252F"); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { //if webview redirects to youtube.com it means we're logged in if ( request.getUrl().toString().startsWith("https://m.youtube.com") || request.getUrl().toString().startsWith("https://www.youtube.com") ) { Log.d(TAG, "Logged in"); Toast.makeText(MainActivity.this, "Logged in", Toast.LENGTH_SHORT).show(); return false; } return false; } }); } ``` -------------------------------- ### Initialize YouTubePlayerView and Load Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Quick-start Initialize the YouTubePlayerView and load a video when the player is ready. Uses AbstractYouTubePlayerListener for simplified event handling. ```java YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player_view); youTubePlayerView.initialize(new YouTubePlayerInitListener() { @Override public void onInitSuccess(final YouTubePlayer initializedYouTubePlayer) { initializedYouTubePlayer.addListener(new AbstractYouTubePlayerListener() { @Override public void onReady() { initializedYouTubePlayer.loadVideo(videoId, 0); } }); } }, true); ``` -------------------------------- ### YouTubePlayerView.initialize(YouTubePlayerListener listener) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initializes the YouTubePlayer. Network events are automatically handled by the player. The argument is a YouTubePlayerListener. ```APIDOC ## YouTubePlayerView.initialize(YouTubePlayerListener) ### Description Initializes the YouTubePlayer. Network events are automatically handled by the player. ### Method ```java YouTubePlayerView.initialize(YouTubePlayerListener listener) ``` ### Parameters #### Path Parameters - **listener** (YouTubePlayerListener) - Required - The listener to handle player events. ``` -------------------------------- ### Kotlin Implementation for Play Next Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Implements the `playNextVideo` method in `WebViewYouTubePlayer` by posting a load URL command to the main thread handler. This executes the JavaScript function to play the next video. ```kotlin override fun playNextVideo() { mainThreadHandler.post { loadUrl("javascript:playNextVideo()") } } ``` -------------------------------- ### YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initializes the YouTubePlayer with control over network event handling and custom IFramePlayerOptions. ```APIDOC ## YouTubePlayerView.initialize(YouTubePlayerListener, boolean, IFramePlayerOptions) ### Description Initializes the YouTubePlayer with control over network event handling and custom IFramePlayerOptions. By passing an `IFramePlayerOptions` to the initialize method it is possible to set some of the parameters of the IFrame YouTubePlayer. ### Method ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions) ``` ### Parameters #### Path Parameters - **listener** (YouTubePlayerListener) - Required - The listener to handle player events. - **handleNetworkEvents** (boolean) - Required - Determines if the player should handle network events. - **iframePlayerOptions** (IFramePlayerOptions) - Required - Options to configure the IFrame player. ``` -------------------------------- ### YouTubePlayerView.initialize(YouTubePlayerListener listener, IFramePlayerOptions iframePlayerOptions) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initializes the YouTubePlayer with custom IFramePlayerOptions. Network events are automatically handled. ```APIDOC ## YouTubePlayerView.initialize(YouTubePlayerListener, IFramePlayerOptions) ### Description Initializes the YouTubePlayer with custom IFramePlayerOptions. Network events are automatically handled by the player. ### Method ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, IFramePlayerOptions iframePlayerOptions) ``` ### Parameters #### Path Parameters - **listener** (YouTubePlayerListener) - Required - The listener to handle player events. - **iframePlayerOptions** (IFramePlayerOptions) - Required - Options to configure the IFrame player. ``` -------------------------------- ### Enable Fullscreen Button Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Configure IFramePlayerOptions to enable the fullscreen button in the YouTube player. ```java IFramePlayerOptions iFramePlayerOptions = new IFramePlayerOptions.Builder(context) .controls(1) .fullscreen(1) .build(); ``` -------------------------------- ### YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions, String videoId) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initializes the YouTubePlayer with control over network event handling, custom IFramePlayerOptions, and immediately loads a specified video. ```APIDOC ## YouTubePlayerView.initialize(YouTubePlayerListener, boolean, IFramePlayerOptions, String) ### Description Initializes the YouTubePlayer with control over network event handling and custom IFramePlayerOptions. By passing the `videoId` the video will be loaded as soon as possible after initialization. ### Method ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions, String videoId) ``` ### Parameters #### Path Parameters - **listener** (YouTubePlayerListener) - Required - The listener to handle player events. - **handleNetworkEvents** (boolean) - Required - Determines if the player should handle network events. - **iframePlayerOptions** (IFramePlayerOptions) - Required - Options to configure the IFrame player. - **videoId** (String) - Required - The ID of the video to load. ``` -------------------------------- ### YouTubePlayerView Initialization Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Initializes the YouTubePlayerView. This method is essential for preparing the player for video playback. It takes a listener to handle initialization success and a boolean to manage network event handling. ```APIDOC ## YouTubePlayerView.initialize ### Description Initializes the YouTubePlayerView and provides a callback for when the player is ready. ### Method `YouTubePlayerView.initialize(YouTubePlayerInitListener listener, boolean handleNetworkEvents)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **listener** (YouTubePlayerInitListener) - Required - The listener to be called when the player is successfully initialized. * **handleNetworkEvents** (boolean) - Required - A boolean indicating whether the library should handle network events. ``` -------------------------------- ### Utility to Load or Cue Video (Kotlin) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Safely loads or cues a video using a Kotlin extension function, preventing autoplay when the Activity is in the background. This function calls loadVideo or cueVideo based on the Activity's lifecycle state. ```kotlin youTubePlayer.loadOrCueVideo(lifeCycle, videoId, startTime) ``` -------------------------------- ### YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents) Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Initializes the YouTubePlayer, allowing control over network event handling. The boolean parameter determines if the player should handle network events. ```APIDOC ## YouTubePlayerView.initialize(YouTubePlayerListener, boolean) ### Description Initializes the YouTubePlayer. By using the `boolean` is possible to decide if the player should handle network events or not. ### Method ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents) ``` ### Parameters #### Path Parameters - **listener** (YouTubePlayerListener) - Required - The listener to handle player events. - **handleNetworkEvents** (boolean) - Required - Determines if the player should handle network events. ``` -------------------------------- ### Add JitPack Repository Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Quick-start Add the JitPack repository to your project-level build.gradle file to download the library. ```gradle allprojects { repositories { ... maven { url "https://jitpack.io" } } } ``` -------------------------------- ### Configure Manifest for OptionsProvider Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the CastOptionsProvider to your AndroidManifest.xml file. Ensure the android:value attribute points to the fully qualified name of your CastOptionsProvider class. ```xml ``` -------------------------------- ### Show Custom Action 1 Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Control the visibility of the first custom action button. ```java PlayerUIController.showCustomAction1(boolean show); ``` -------------------------------- ### Set Custom Player UI View Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Alternatively, you can set a pre-inflated View object as the custom player UI. ```java void setCustomPlayerUi(View view) ``` -------------------------------- ### Set Custom Action 2 Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Configure a custom action button on the left side of the Play/Pause button. The action is only visible if a non-null listener is provided. ```java PlayerUIController.setCustomAction2(Drawable icon, OnClickListener listener ); ``` -------------------------------- ### Listen to Fullscreen Events Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Implement FullscreenListener to handle entering and exiting fullscreen mode. The fullscreen view must be added to the hierarchy when entering fullscreen. ```java youTubePlayerView.addFullscreenListener(new FullscreenListener() { @Override public void onEnterFullscreen(@NonNull View fullscreenView, @NonNull Function0 exitFullscreen) { } @Override public void onExitFullscreen() { } }); ``` -------------------------------- ### Initialize YouTubePlayerView Programmatically Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Use these methods to initialize the YouTubePlayerView after disabling automatic initialization. Choose the method that best suits your needs for handling network events and IFrame player options. ```java YouTubePlayerView.initialize(YouTubePlayerListener listener) ``` ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, IFramePlayerOptions iframePlayerOptions) ``` ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents) ``` ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions) ``` ```java YouTubePlayerView.initialize(YouTubePlayerListener listener, boolean handleNetworkEvents, IFramePlayerOptions iframePlayerOptions, String videoId) ``` -------------------------------- ### Implement setPlaybackQuality in YouTubePlayer Interface Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Defines the `setPlaybackQuality` method in the `YoutubePlayer` interface, which will be implemented by `WebViewYouTubePlayer` to control video playback quality. ```kotlin fun setPlaybackQuality(quality: String) ``` -------------------------------- ### Implement setPlaybackQuality in WebViewYouTubePlayer Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Implements the `setPlaybackQuality` method for `WebViewYouTubePlayer`. This function loads a JavaScript call into the webview to change the video playback quality. ```kotlin override fun setPlaybackQuality(quality: String) { mainThreadHandler.post { loadUrl("javascript:setPlaybackQuality('$quality')") } } ``` -------------------------------- ### Set Custom YouTubePlayerMenu Implementation Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Menu Replace the default menu implementation with your own custom YouTubePlayerMenu. ```Java PlayerUIController.setMenu(YouTubePlayerMenu youTubePlayerMenu); ``` -------------------------------- ### Add Custom UI Dependency Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the core and custom-ui modules to your app's build.gradle file to use the DefaultPlayerUiController. ```gradle dependencies { implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:{latest-version}' implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:custom-ui:{latest-version}' } ``` -------------------------------- ### Show Custom Action 2 Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Control the visibility of the second custom action button. ```java PlayerUIController.showCustomAction2(boolean show); ``` -------------------------------- ### Show and Dismiss YouTubePlayerMenu Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Control the visibility of the YouTubePlayerMenu by calling show() with an anchor view or dismiss() to hide it. ```java void show(View anchorView) void dismiss() ``` -------------------------------- ### Implement CastOptionsProvider Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Declare a CastOptionsProvider in your project to initialize the Cast context. This requires registering a custom receiver on the Google Cast SDK Developer Console to obtain a receiver application ID. ```java 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.Builder() .setReceiverApplicationId(receiverId) .build(); } public List getAdditionalSessionProviders(Context context) { return null; } } ``` -------------------------------- ### Add Core Dependency Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the core module dependency to your module-level build.gradle file to include the YouTube Player functionality. ```gradle dependencies { implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:13.0.0' } ``` -------------------------------- ### Inflate Custom Player UI Layout Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Use this method to inflate a custom layout for the player's UI. The layout will be overlayed on top of the player. ```java View inflateCustomPlayerUi(@LayoutRes int customUiLayoutID) ``` -------------------------------- ### Utility to Load or Cue Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Safely loads or cues a video, preventing autoplay when the Activity is in the background. This utility handles the logic of calling loadVideo or cueVideo based on the Activity's lifecycle state. ```java YouTubePlayerUtils.loadOrCueVideo( youTubePlayer, getLifecycle(), videoId, startTime ); ``` -------------------------------- ### Set Custom Action 1 Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Configure a custom action button on the right side of the Play/Pause button. The action is only visible if a non-null listener is provided. ```java PlayerUIController.setCustomAction1(Drawable icon, OnClickListener listener ); ``` -------------------------------- ### Configure Activity for Fullscreen Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the android:configChanges attribute to your Activity in the manifest to handle orientation and screen size changes during fullscreen playback. ```xml ``` -------------------------------- ### Proguard Configuration Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Quick-start If you are using ProGuard, add these options to your ProGuard configuration file to prevent obfuscation of the library classes. ```proguard -keep public class com.pierfrancescosoffritti.youtubeplayer.** { public *; } -keepnames class com.pierfrancescosoffritti.youtubeplayer.* ``` -------------------------------- ### YouTubePlayerView Fullscreen Controls Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Provides methods to manage the fullscreen state of the YouTube player. You can enter, exit, toggle, and check the current fullscreen status. ```APIDOC ## YouTubePlayerView Fullscreen Methods ### Description Methods to control and query the fullscreen state of the YouTube player. ### Methods * `YouTubePlayerView.enterFullScreen()`: Enters fullscreen mode. * `YouTubePlayerView.exitFullScreen()`: Exits fullscreen mode. * `YouTubePlayerView.isFullScreen()`: Returns `true` if the player is currently in fullscreen mode, `false` otherwise. * `YouTubePlayerView.toggleFullScreen()`: Toggles between fullscreen and normal mode. ``` -------------------------------- ### YouTubePlayerListener Interface Methods Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Defines the methods that must be implemented to listen for YouTubePlayer events. ```java // Called when the player is ready to play videos. // You should start using the player only after this method is called. void onReady(@NonNull YouTubePlayer youTubePlayer) // Called every time the state of the player changes. void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state) // 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 error) // Called periodically by the player, the argument is the number of seconds that have been played. void onCurrentSecond(@NonNull YouTubePlayer youTubePlayer, float second) // Called when the total duration of the video is loaded. // Note that getDuration() will return 0 until the video's metadata is loaded, which normally happens just after the video starts playing. void onVideoDuration(@NonNull YouTubePlayer youTubePlayer, float duration) // Called periodically by the player, the argument is the percentage 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, String videoId) void onApiChange(@NonNull YouTubePlayer youTubePlayer) ``` -------------------------------- ### Implement ChromecastConnectionListener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Implement this listener to handle Chromecast connection events. It provides callbacks for connecting, connected, and disconnected states. The `onChromecastConnected` callback is where you initialize the cast player. ```java private 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); } }); } } ``` -------------------------------- ### Add MediaRouterButton to Layout Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Include a MediaRouteButton in your XML layout file to allow users to initiate casting. This button will be automatically configured to interact with the Google Cast framework. ```xml ``` -------------------------------- ### Inflate Custom Player UI Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Replace-the-player's-UI Use this method to replace the default player UI with a custom layout resource. After inflation, the default PlayerUIController is no longer accessible. ```java View customPlayerUI = youTubePlayerView.inflateCustomPlayerUI(R.layout.custom_player_ui); youTubePlayerView.initialize(youTubePlayer -> { CustomPlayerUIController customPlayerUIController = new CustomPlayerUIController(this, customPlayerUI, youTubePlayer, youTubePlayerView); youTubePlayer.addListener(customPlayerUIController); youTubePlayerView.addFullScreenListener(customPlayerUIController); // ... }, true); ``` -------------------------------- ### IFramePlayerOptions Builder Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Provides a way to construct IFramePlayerOptions objects to customize the IFrame YouTubePlayer. ```APIDOC ## IFramePlayerOptions Builder ### Description The `IFramePlayerOptions` is an optional argument that can be passed to `YouTubePlayerView.initialize`, it can be used to set some of the parameters of the IFrame YouTubePlayer. Use the Builder to get an `IFramePlayerOptions` object. ### Example ```java IFramePlayerOptions iFramePlayerOptions = new IFramePlayerOptions.Builder(context) .controls(1) .build(); ``` ### Supported Options - **controls** (int) - 0: web UI is not visible, 1: web UI is visible. - **rel** (int) - 0: related videos from the same channel, 1: related videos from multiple channels. - **ivLoadPolicy** (int) - 1: show annotations, 3: hide annotations. - **ccLoadPolicy** (int) - 0: show captions, 1: hide captions. Does not work with automatically generated captions. - **start** (int) - The time in seconds from the start of the video to begin playing. - **end** (int) - The time in seconds from the beginning of the video when the player should stop playing. ``` -------------------------------- ### JavaScript to Play Next Recommended Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md This JavaScript function finds the next suggested video from the YouTube player's suggestions and loads it. It extracts the video ID from the link and handles potential extra parameters. ```javascript function playNextVideo() { const playerIFrame = document.querySelector("iframe"); if (!playerIFrame) { return; } const frameDoc = playerIFrame.contentDocument; if (!frameDoc) { return; } const nextVideo = frameDoc.querySelectorAll('.ytp-suggestions a') if(!nextVideo){ return; } let videoId = nextVideo[0].href.split('v=')[1]; let ampersandIndex = videoId.indexOf('&'); if (ampersandIndex != -1) { videoId = videoId.substring(0, ampersandIndex); } player.loadVideoById(videoId, 0); } ``` -------------------------------- ### Play Previous Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Skips to the previous video in the current playlist. ```javascript function previousVideo() { player.previousVideo(); } ``` -------------------------------- ### Handle Video Quality Events in Kotlin Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md This Kotlin function is exposed to JavaScript via `@JavascriptInterface` to receive video quality information from the webview. It then notifies listeners of the YouTube player owner. ```kotlin @JavascriptInterface fun sendVideoQuality(quality: String) { mainThreadHandler.post { for(listener in youTubePlayerOwner.getListeners()) { // also add this new method to the listener interface listener.onVideoQuality(youTubePlayerOwner.getInstance(), quality) } } } ``` -------------------------------- ### Play Next Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Skips to the next video in the current playlist. ```javascript function nextVideo() { player.nextVideo(); } ``` -------------------------------- ### Player State Change Handling Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Handles changes in the YouTube player's state, such as unstarted, playing, paused, or buffering. It also manages intervals for sending current playback time and loaded fraction. ```javascript function sendPlayerStateChange(playerState) { clearTimeout(timerId); switch (playerState) { case YT.PlayerState.UNSTARTED: sendStateChange(UNSTARTED); sendVideoIdFromPlaylistIfAvailable(player); return; case YT.PlayerState.ENDED: sendStateChange(ENDED); return; case YT.PlayerState.PLAYING: sendStateChange(PLAYING); startSendCurrentTimeInterval(); sendVideoData(player); return; case YT.PlayerState.PAUSED: sendStateChange(PAUSED); return; case YT.PlayerState.BUFFERING: sendStateChange(BUFFERING); return; case YT.PlayerState.CUED: sendStateChange(CUED); return; } function sendVideoData(player) { var videoDuration = player.getDuration(); YouTubePlayerBridge.sendVideoDuration(videoDuration); } // This method checks if the player is playing a playlist. // If yes, it sends out the video id of the video being played. function sendVideoIdFromPlaylistIfAvailable(player) { var playlist = player.getPlaylist(); if ( typeof playlist !== 'undefined' && Array.isArray(playlist) && playlist.length > 0 ) { var index = player.getPlaylistIndex(); var videoId = playlist[index]; YouTubePlayerBridge.sendVideoId(videoId); } } function sendStateChange(newState) { YouTubePlayerBridge.sendStateChange(newState) } function startSendCurrentTimeInterval() { timerId = setInterval(function() { YouTubePlayerBridge.sendVideoCurrentTime( player.getCurrentTime() ) YouTubePlayerBridge.sendVideoLoadedFraction( player.getVideoLoadedFraction() ) }, 100 ); } } ``` -------------------------------- ### Add Menu Item to Default Menu Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Menu Add a MenuItem to the default YouTubePlayerMenu. The menu is initially empty. ```Java YouTubePlayerMenu.addItem(MenuItem menuItem); ``` -------------------------------- ### YouTubePlayerView XML Attributes Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Documentation for the XML attributes available for customizing the YouTubePlayerView. These attributes allow for configuration of video playback, initialization, and network event handling directly within the layout. ```APIDOC ## YouTubePlayerView XML Attributes ### Description Custom attributes to configure the `YouTubePlayerView`'s appearance and behavior when added to an XML layout. ### Attributes #### videoId - **Type**: String - **Description**: The ID of the YouTube video to be played. If set, the player will attempt to play this video automatically. Best practice for single-video players. #### autoPlay - **Type**: Boolean - **Default**: `false` - **Description**: If `true`, the player starts playing the video specified by `videoId` without user interaction. Requires `videoId` to be set and the view to be added as a `LifecycleObserver`. If `videoId` is not set, this attribute is ignored. If set to `true` without `videoId`, an exception will be thrown. #### enableAutomaticInitialization - **Type**: Boolean - **Default**: `true` - **Description**: If `true`, `YouTubePlayerView` handles its own initialization. If `false`, manual initialization is required, typically when using `IFramePlayerOptions`. #### handleNetworkEvents - **Type**: Boolean - **Default**: `true` - **Description**: If `true`, `YouTubePlayerView` manages network events using a `NetworkReceiver` to resume initialization on network recovery. If `false`, network event handling is the responsibility of the developer. Setting this to `false` often implies disabling `enableAutomaticInitialization` as well. ``` -------------------------------- ### Set Playlist Loop Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Enables or disables looping for the current playlist. Set to true to loop, false otherwise. ```javascript function setLoop(loop) { player.setLoop(loop); } ``` -------------------------------- ### Manage YouTubePlayerMenu Items Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add or remove MenuItem objects from the YouTubePlayerMenu. Initially, the menu is empty and requires items to be added. ```java YouTubePlayerMenu addItem(MenuItem menuItem) YouTubePlayerMenu removeItem(MenuItem menuItem) YouTubePlayerMenu removeItem(int itemIndex) ``` -------------------------------- ### Play Video at Index Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Plays a specific video from the playlist based on its index. ```javascript function playVideoAt(index) { player.playVideoAt(index); } ``` -------------------------------- ### YouTubePlayerView LifecycleObserver Integration Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Demonstrates how to integrate YouTubePlayerView with Android's LifecycleObserver to automatically manage player lifecycle events like pausing and releasing. ```APIDOC ## YouTubePlayerView Lifecycle Integration ### Description Integrates the `YouTubePlayerView` with Android's `LifecycleObserver` for automatic lifecycle event handling. ### Usage Add the `YouTubePlayerView` as an observer to your Activity or Fragment's lifecycle. ```java lifecycleOwner.getLifecycle().addObserver(youTubePlayerView); ``` This integration will automatically pause playback when the associated Activity/Fragment stops and call `release()` when it's destroyed. If you need the player to continue playing when the Activity/Fragment is paused (e.g., for multi-window support, though this may violate Play Store policies), you should not register it as a lifecycle observer and instead manually call `release()` in `onDestroy()`. ``` -------------------------------- ### YouTube IFrame API Ready Handler Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/chromecast-receiver/index.html This function is automatically called by the IFrame APIs when the YouTube player is ready. It ensures that the main onYouTubeIframeAPIReady function is called, allowing for custom initialization logic. ```javascript // called automatically by the IFrame APIs function onYouTubeIframeAPIReady() { window.main_onYouTubeIframeAPIReady() } ``` -------------------------------- ### Kotlin Interface for Play Next Video Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Defines the `playNextVideo` method within the `YouTubePlayer` interface. This allows the functionality to be called from the Android application. ```kotlin fun playNextVideo() ``` -------------------------------- ### Configure FadeViewHelper Animation Properties Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Set the animation duration and fade-out delay for the FadeViewHelper using its setter methods. Times are in milliseconds. ```java fadeViewHelper.setAnimationDuration(FadeViewHelper.DEFAULT_ANIMATION_DURATION); fadeViewHelper.setFadeOutDelay(FadeViewHelper.DEFAULT_FADE_OUT_DELAY); ``` -------------------------------- ### Add Library Dependency Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Quick-start Add the Android-YouTube-Player library dependency to your module-level build.gradle file. ```gradle dependencies { implementation 'com.github.PierfrancescoSoffritti:AndroidYouTubePlayer:7.0.1' } ``` -------------------------------- ### Add YouTubePlayerSeekBar as a Listener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Register the YouTubePlayerSeekBar as a listener to your YouTubePlayer instance to enable its functionality. ```java youTubePlayer.addListener(youTubePlayerSeekBar); ``` -------------------------------- ### YouTubePlayerView PlayerUIController Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Retrieves the PlayerUIController, which allows interaction with the player's user interface elements. ```APIDOC ## YouTubePlayerView.getPlayerUIController ### Description Gets a reference to the PlayerUIController for interacting with the player's UI. ### Method `PlayerUIController YouTubePlayerView.getPlayerUIController()` ### Returns A `PlayerUIController` instance. ``` -------------------------------- ### YouTubePlayerView Full Screen Controls Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Methods to control the full-screen mode of the YouTubePlayerView. These include entering, exiting, checking the status, and toggling full screen. ```java YouTubePlayerView.enterFullScreen(); YouTubePlayerView.exitFullScreen(); YouTubePlayerView.isFullScreen(); YouTubePlayerView.toggleFullScreen(); ``` -------------------------------- ### Add Full Screen Listener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Register a listener to be notified when the YouTubePlayerView enters or exits full-screen mode. Remember that the library does not handle Activity orientation changes. ```java YouTubePlayerView.addFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener); YouTubePlayerView.removeFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener); ``` -------------------------------- ### Enable DOM Storage in WebView Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Enable DOM storage in the WebView settings to allow access to localStorage. This is a prerequisite for changing video quality via localStorage. ```kotlin settings.domStorageEnabled = true ``` -------------------------------- ### Handle Seek Events from YouTubePlayerSeekBar Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Implement the YouTubePlayerSeekBarListener to update the YouTubePlayer's playback position when the user interacts with the seek bar. ```java youTubePlayerSeekBar.setYoutubePlayerSeekBarListener(new YouTubePlayerSeekBarListener() { @Override public void seekTo(float time) { youTubePlayer.seekTo(time); } }); ``` -------------------------------- ### Control Menu Button Visibility Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Menu Use these methods to show or hide the menu button. The menu button is hidden by default. ```Java PlayerUIController.showMenuButton(boolean show); ``` -------------------------------- ### Add YouTubePlayerSeekBar to XML Layout Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Declare the YouTubePlayerSeekBar in your XML layout file. You can customize font size and color using attributes. ```xml ``` -------------------------------- ### Enable Captions Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md This function enables captions for the YouTube player by loading the captions module. Call this function when you want to display captions. ```javascript function hideCaption() { if(!player) { return; } player.loadModule('captions'); } ``` -------------------------------- ### JavaScript Functions for Video Quality Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md These JavaScript functions interact with the YouTube player's localStorage to manage video quality. `sendVideoQuality` retrieves available quality levels, and `setPlaybackQuality` sets a specific quality or resets to auto. ```javascript // Return the available quality options for the current video. // Not all videos have the same quality options, so we need to check what's available first. // this function will return an array like: ["hd1080","hd720","large","medium","small","tiny","auto"] function sendVideoQuality(player) { YouTubePlayerBridge.sendVideoQuality(JSON.stringify(player.getAvailableQualityLevels())) } function setPlaybackQuality(playbackQuality) { if (playbackQuality == "auto") { localStorage.removeItem("yt-player-quality"); } else { var now = Date.now(); // this will set `playbackQuality` as the selected video quality, untile it expires localStorage.setItem("yt-player-quality", JSON.stringify({ data: playbackQuality, creation: now, expiration: now + 2419200000 })); } // after changing the quality you need to reload the video to see changes. // reload the video and start playing where it was. if (player) { var currentTime = player.getCurrentTime(); player.loadVideoById(player.getVideoData().video_id, currentTime); } } ``` -------------------------------- ### Add FadeViewHelper as a Listener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the FadeViewHelper as a listener to your YouTubePlayer instance to enable its automatic fading behavior based on player state. ```java youTubePlayer.addListener(fadeViewHelper); ``` -------------------------------- ### Set Player Volume Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Sets the volume of the YouTube player to a specified percentage (0-100). ```javascript function setVolume(volumePercent) { player.setVolume(volumePercent); } ``` -------------------------------- ### Add YouTubePlayerListener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerListener Use this method to add a listener to receive events from the YouTubePlayer. ```java YouTubePlayer.addListener(YouTubePlayerListener listener); ``` -------------------------------- ### Add View to Player UI Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/PlayerUIController Add a custom View to the top of the player's UI. This can be used for adding new icons or other UI elements. ```java PlayerUIController.addView(View view); ``` -------------------------------- ### Set Custom Menu Button Click Listener Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Menu Assign a custom OnClickListener to the menu button. The default listener displays the standard menu. ```Java PlayerUIController.setMenuButtonClickListener(@NonNull View.OnClickListener customMenuButtonClickListener); ``` -------------------------------- ### Set Playlist Shuffle Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/core/src/main/res/raw/ayp_youtube_player.html Enables or disables shuffling of the current playlist. Set to true to shuffle, false otherwise. ```javascript function setShuffle(shuffle) { player.setShuffle(shuffle); } ``` -------------------------------- ### Format Time in Seconds Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Utilize the TimeUtilities.formatTime method to convert a time value in seconds into a human-readable 'M:SS' string format. ```java String TimeUtilities.formatTime(float timeInSeconds) ``` -------------------------------- ### Add Chromecast Sender Dependency Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Add the chromecast-sender module dependency to your module-level build.gradle file to enable casting YouTube videos to a Chromecast device. ```gradle dependencies { implementation 'com.pierfrancescosoffritti.androidyoutubeplayer:chromecast-sender:0.32' } ``` -------------------------------- ### Track YouTube Player State Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/Utilities Use YouTubePlayerStateTracker to listen for state changes and retrieve player information. Add the tracker as a listener to your YouTubePlayer instance. ```java YouTubePlayerStateTracker tracker = new YouTubePlayerStateTracker(); youTubePlayer.addListener(tracker); tracker.getCurrentState(); tracker.getCurrentSecond(); tracker.getVideoDuration(); tracker.getVideoId(); ``` -------------------------------- ### Control Menu Button Visibility Source: https://github.com/pierfrancescosoffritti/android-youtube-player/blob/dev/README.md Use PlayerUiController.showMenuButton(boolean) to control the visibility of the menu button. By default, the menu icon is not visible. ```java PlayerUiController.showMenuButton(boolean show); ``` -------------------------------- ### Observe Lifecycle for Automatic Release Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Implement LifecycleObserver to automatically release the YouTubePlayerView when the associated Activity or Fragment is destroyed. Playback also pauses when the Activity/Fragment stops, which is suitable for multi-window support. ```java lifecycleOwner.getLifecycle().addObserver(youTubePlayerView); ``` -------------------------------- ### YouTubePlayerView Fullscreen Listeners Source: https://github.com/pierfrancescosoffritti/android-youtube-player/wiki/YouTubePlayerView Allows you to add and remove listeners to be notified when the YouTube player enters or exits fullscreen mode. ```APIDOC ## YouTubePlayerView Fullscreen Listeners ### Description Methods to manage listeners for fullscreen state changes. ### Methods * `YouTubePlayerView.addFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener)`: Adds a listener to be notified of fullscreen events. * `YouTubePlayerView.removeFullScreenListener(YouTubePlayerFullScreenListener fullScreenListener)`: Removes a previously added fullscreen listener. ```