├── .gitignore ├── LICENSE ├── README.md ├── VideoEnabledWebView.iml ├── app ├── app.iml ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── name │ │ └── cpr │ │ ├── ExampleActivity.java │ │ ├── VideoEnabledWebChromeClient.java │ │ └── VideoEnabledWebView.java │ └── res │ ├── drawable-hdpi │ └── ic_launcher.png │ ├── drawable-mdpi │ └── ic_launcher.png │ ├── drawable-xhdpi │ └── ic_launcher.png │ ├── drawable-xxhdpi │ └── ic_launcher.png │ ├── layout │ ├── activity_example.xml │ └── view_loading_video.xml │ └── values │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | /.gradle 2 | /.idea 3 | /build 4 | /app/build 5 | local.properties -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Cristian Perez 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | VideoEnabledWebView 2 | =================== 3 | 4 | Android's WebView and WebChromeClient class extensions that enable fully working, cross-device, HTML5 video support in Android 2.2 (API level 8) onwards. Actively maintained and tested up to Android 4.4 (API level 19) with its new Chromium webview. 5 | 6 | Motivation 7 | ---------- 8 | 9 | Android's default WebView doesn't work well with HTML5 videos (i.e. the _<video>_ tag). Unlike iOS's UIWebView, which is similar to a Safari tab with respect to video handling, Android's implementation is far from how a Chrome tab behaves. API level fragmentation and manufacturer customizations, which usually include video player related UI changes, only add up to the mess. Things that don't work consistently across devices include: 10 | - Videos not even playing. 11 | - Videos not playing in-line. 12 | - Videos not displaying any status indicator while loading. 13 | - Videos not going full-screen. 14 | - Videos not automatically exiting full-screen when they end. 15 | - Videos not playing for the second time. 16 | 17 | VideoEnabledWebView and VideoEnabledWebChromeClient are two handy extension classes that come to help deal with these issues. I originally wrote them for my personal use, but they got a lot of attention in [StackOverflow](http://stackoverflow.com/a/16179544/423171), and that's the reason they are now here. Contributions are appreciated. 18 | 19 | How to use it 20 | ------------- 21 | 22 | For a working example, download the whole repository and open it with __Android Studio__. Do not use the Open Project option, use __Import Project__. 23 | 24 | As you can see in the example project, you first need to include __VideoEnabledWebView.java__ and __VideoEnabledWebChromeClient.java__ classes into your project. Second, you need to carefully read both classes' comments, as they are fully documented with javadoc and include very important information on how to use them correctly based on your needs. 25 | 26 | VideoEnabledWebChromeClient can be used alone if you do not require the functionality that VideoEnabledWebView adds, although you need to include both classes anyway in order to compile. On the other side, __VideoEnabledWebView must always rely on a VideoEnabledWebChromeClient__. 27 | 28 | Finally, you need to define all the views that you will be using in your layout files, and provide the relevant references in the classes' constructors. 29 | 30 | Common issues check-list 31 | ------------------------ 32 | 33 | 1. Remember to declare the __internet permission__ in AndroidManifest.xml if you are using the WebView to access remote content: `` 34 | 2. Remember to enable __hardware acceleration__ in AndroidManifest.xml for in-line videos to work in API level 11. The field will have no effect in earlier API levels: `android:hardwareAccelerated="true"` 35 | 3. Remember to __initialize the VideoEnabledWebChromeClient__ and link it with the VideoEnabledWebView. Follow the example in ExampleActivity.java. 36 | 4. Remember to override your Activity's __onBackPressed()__ and pass the event to the VideoEnabledWebChromeClient. Follow the example in ExampleActivity.java. 37 | 5. Remember to specify and/or programmatically inflate the __videoLayout__, __nonVideoLayout__, and, optionally, __loadingView__. Follow the example in ExampleActivity.java and the xml layout files in res/layout. 38 | 6. If you are using __ProGuard__, remember to add the fully qualified name of the Javascript interface to the rules file: `-keepclassmembers class name.cpr.VideoEnabledWebView$JavascriptInterface { public *; }` 39 | -------------------------------------------------------------------------------- /VideoEnabledWebView.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 22 5 | buildToolsVersion '25.0.0' 6 | 7 | defaultConfig { 8 | applicationId "cpr.name.videoenabledwebview" 9 | minSdkVersion 8 10 | targetSdkVersion 22 11 | versionCode 2 12 | versionName "1.0.1" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | compile 'com.android.support:appcompat-v7:22.0.0' 25 | } 26 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Program Files\Android Studio\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | -keepclassmembers class name.cpr.VideoEnabledWebView$JavascriptInterface { 16 | public *; 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/src/main/java/name/cpr/ExampleActivity.java: -------------------------------------------------------------------------------- 1 | package name.cpr; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.ActionBarActivity; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.view.WindowManager; 8 | import android.webkit.WebView; 9 | import android.webkit.WebViewClient; 10 | 11 | import cpr.name.videoenabledwebview.R; 12 | 13 | public class ExampleActivity extends ActionBarActivity 14 | { 15 | private VideoEnabledWebView webView; 16 | private VideoEnabledWebChromeClient webChromeClient; 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) 20 | { 21 | super.onCreate(savedInstanceState); 22 | setContentView(R.layout.activity_example); 23 | 24 | // Save the web view 25 | webView = (VideoEnabledWebView)findViewById(R.id.webView); 26 | 27 | // Initialize the VideoEnabledWebChromeClient and set event handlers 28 | View nonVideoLayout = findViewById(R.id.nonVideoLayout); // Your own view, read class comments 29 | ViewGroup videoLayout = (ViewGroup)findViewById(R.id.videoLayout); // Your own view, read class comments 30 | //noinspection all 31 | View loadingView = getLayoutInflater().inflate(R.layout.view_loading_video, null); // Your own view, read class comments 32 | webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, webView) // See all available constructors... 33 | { 34 | // Subscribe to standard events, such as onProgressChanged()... 35 | @Override 36 | public void onProgressChanged(WebView view, int progress) 37 | { 38 | // Your code... 39 | } 40 | }; 41 | webChromeClient.setOnToggledFullscreen(new VideoEnabledWebChromeClient.ToggledFullscreenCallback() 42 | { 43 | @Override 44 | public void toggledFullscreen(boolean fullscreen) 45 | { 46 | // Your code to handle the full-screen change, for example showing and hiding the title bar. Example: 47 | if (fullscreen) 48 | { 49 | WindowManager.LayoutParams attrs = getWindow().getAttributes(); 50 | attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; 51 | attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 52 | getWindow().setAttributes(attrs); 53 | if (android.os.Build.VERSION.SDK_INT >= 14) 54 | { 55 | //noinspection all 56 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); 57 | } 58 | } 59 | else 60 | { 61 | WindowManager.LayoutParams attrs = getWindow().getAttributes(); 62 | attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN; 63 | attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; 64 | getWindow().setAttributes(attrs); 65 | if (android.os.Build.VERSION.SDK_INT >= 14) 66 | { 67 | //noinspection all 68 | getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); 69 | } 70 | } 71 | 72 | } 73 | }); 74 | webView.setWebChromeClient(webChromeClient); 75 | // Call private class InsideWebViewClient 76 | webView.setWebViewClient(new InsideWebViewClient()); 77 | 78 | // Navigate anywhere you want, but consider that this classes have only been tested on YouTube's mobile site 79 | webView.loadUrl("http://m.youtube.com"); 80 | 81 | } 82 | 83 | private class InsideWebViewClient extends WebViewClient { 84 | @Override 85 | // Force links to be opened inside WebView and not in Default Browser 86 | // Thanks http://stackoverflow.com/a/33681975/1815624 87 | public boolean shouldOverrideUrlLoading(WebView view, String url) { 88 | view.loadUrl(url); 89 | return true; 90 | } 91 | } 92 | 93 | @Override 94 | public void onBackPressed() 95 | { 96 | // Notify the VideoEnabledWebChromeClient, and handle it ourselves if it doesn't handle it 97 | if (!webChromeClient.onBackPressed()) 98 | { 99 | if (webView.canGoBack()) 100 | { 101 | webView.goBack(); 102 | } 103 | else 104 | { 105 | // Standard back button implementation (for example this could close the app) 106 | super.onBackPressed(); 107 | } 108 | } 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /app/src/main/java/name/cpr/VideoEnabledWebChromeClient.java: -------------------------------------------------------------------------------- 1 | package name.cpr; 2 | 3 | import android.media.MediaPlayer; 4 | import android.view.SurfaceView; 5 | import android.view.View; 6 | import android.view.ViewGroup; 7 | import android.webkit.WebChromeClient; 8 | import android.widget.FrameLayout; 9 | 10 | /** 11 | * This class serves as a WebChromeClient to be set to a WebView, allowing it to play video. 12 | * Video will play differently depending on target API level (in-line, fullscreen, or both). 13 | * 14 | * It has been tested with the following video classes: 15 | * - android.widget.VideoView (typically API level <11) 16 | * - android.webkit.HTML5VideoFullScreen$VideoSurfaceView/VideoTextureView (typically API level 11-18) 17 | * - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView (typically API level 19+) 18 | * 19 | * Important notes: 20 | * - For API level 11+, android:hardwareAccelerated="true" must be set in the application manifest. 21 | * - The invoking activity must call VideoEnabledWebChromeClient's onBackPressed() inside of its own onBackPressed(). 22 | * - Tested in Android API levels 8-19. Only tested on http://m.youtube.com. 23 | * 24 | * @author Cristian Perez (http://cpr.name) 25 | * 26 | */ 27 | public class VideoEnabledWebChromeClient extends WebChromeClient implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener 28 | { 29 | public interface ToggledFullscreenCallback 30 | { 31 | public void toggledFullscreen(boolean fullscreen); 32 | } 33 | 34 | private View activityNonVideoView; 35 | private ViewGroup activityVideoView; 36 | private View loadingView; 37 | private VideoEnabledWebView webView; 38 | 39 | private boolean isVideoFullscreen; // Indicates if the video is being displayed using a custom view (typically full-screen) 40 | private FrameLayout videoViewContainer; 41 | private CustomViewCallback videoViewCallback; 42 | 43 | private ToggledFullscreenCallback toggledFullscreenCallback; 44 | 45 | /** 46 | * Never use this constructor alone. 47 | * This constructor allows this class to be defined as an inline inner class in which the user can override methods 48 | */ 49 | @SuppressWarnings("unused") 50 | public VideoEnabledWebChromeClient() 51 | { 52 | } 53 | 54 | /** 55 | * Builds a video enabled WebChromeClient. 56 | * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. 57 | * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. 58 | */ 59 | @SuppressWarnings("unused") 60 | public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView) 61 | { 62 | this.activityNonVideoView = activityNonVideoView; 63 | this.activityVideoView = activityVideoView; 64 | this.loadingView = null; 65 | this.webView = null; 66 | this.isVideoFullscreen = false; 67 | } 68 | 69 | /** 70 | * Builds a video enabled WebChromeClient. 71 | * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. 72 | * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. 73 | * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view. 74 | */ 75 | @SuppressWarnings("unused") 76 | public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView) 77 | { 78 | this.activityNonVideoView = activityNonVideoView; 79 | this.activityVideoView = activityVideoView; 80 | this.loadingView = loadingView; 81 | this.webView = null; 82 | this.isVideoFullscreen = false; 83 | } 84 | 85 | /** 86 | * Builds a video enabled WebChromeClient. 87 | * @param activityNonVideoView A View in the activity's layout that contains every other view that should be hidden when the video goes full-screen. 88 | * @param activityVideoView A ViewGroup in the activity's layout that will display the video. Typically you would like this to fill the whole layout. 89 | * @param loadingView A View to be shown while the video is loading (typically only used in API level <11). Must be already inflated and not attached to a parent view. 90 | * @param webView The owner VideoEnabledWebView. Passing it will enable the VideoEnabledWebChromeClient to detect the HTML5 video ended event and exit full-screen. 91 | * Note: The web page must only contain one video tag in order for the HTML5 video ended event to work. This could be improved if needed (see Javascript code). 92 | */ 93 | @SuppressWarnings("unused") 94 | public VideoEnabledWebChromeClient(View activityNonVideoView, ViewGroup activityVideoView, View loadingView, VideoEnabledWebView webView) 95 | { 96 | this.activityNonVideoView = activityNonVideoView; 97 | this.activityVideoView = activityVideoView; 98 | this.loadingView = loadingView; 99 | this.webView = webView; 100 | this.isVideoFullscreen = false; 101 | } 102 | 103 | /** 104 | * Indicates if the video is being displayed using a custom view (typically full-screen) 105 | * @return true it the video is being displayed using a custom view (typically full-screen) 106 | */ 107 | public boolean isVideoFullscreen() 108 | { 109 | return isVideoFullscreen; 110 | } 111 | 112 | /** 113 | * Set a callback that will be fired when the video starts or finishes displaying using a custom view (typically full-screen) 114 | * @param callback A VideoEnabledWebChromeClient.ToggledFullscreenCallback callback 115 | */ 116 | @SuppressWarnings("unused") 117 | public void setOnToggledFullscreen(ToggledFullscreenCallback callback) 118 | { 119 | this.toggledFullscreenCallback = callback; 120 | } 121 | 122 | @Override 123 | public void onShowCustomView(View view, CustomViewCallback callback) 124 | { 125 | if (view instanceof FrameLayout) 126 | { 127 | // A video wants to be shown 128 | FrameLayout frameLayout = (FrameLayout) view; 129 | View focusedChild = frameLayout.getFocusedChild(); 130 | 131 | // Save video related variables 132 | this.isVideoFullscreen = true; 133 | this.videoViewContainer = frameLayout; 134 | this.videoViewCallback = callback; 135 | 136 | // Hide the non-video view, add the video view, and show it 137 | activityNonVideoView.setVisibility(View.INVISIBLE); 138 | activityVideoView.addView(videoViewContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 139 | activityVideoView.setVisibility(View.VISIBLE); 140 | 141 | if (focusedChild instanceof android.widget.VideoView) 142 | { 143 | // android.widget.VideoView (typically API level <11) 144 | android.widget.VideoView videoView = (android.widget.VideoView) focusedChild; 145 | 146 | // Handle all the required events 147 | videoView.setOnPreparedListener(this); 148 | videoView.setOnCompletionListener(this); 149 | videoView.setOnErrorListener(this); 150 | } 151 | else 152 | { 153 | // Other classes, including: 154 | // - android.webkit.HTML5VideoFullScreen$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 11-18) 155 | // - android.webkit.HTML5VideoFullScreen$VideoTextureView, which inherits from android.view.TextureView (typically API level 11-18) 156 | // - com.android.org.chromium.content.browser.ContentVideoView$VideoSurfaceView, which inherits from android.view.SurfaceView (typically API level 19+) 157 | 158 | // Handle HTML5 video ended event only if the class is a SurfaceView 159 | // Test case: TextureView of Sony Xperia T API level 16 doesn't work fullscreen when loading the javascript below 160 | if (webView != null && webView.getSettings().getJavaScriptEnabled() && focusedChild instanceof SurfaceView) 161 | { 162 | // Run javascript code that detects the video end and notifies the Javascript interface 163 | String js = "javascript:"; 164 | js += "var _ytrp_html5_video_last;"; 165 | js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];"; 166 | js += "if (_ytrp_html5_video != undefined && _ytrp_html5_video != _ytrp_html5_video_last) {"; 167 | { 168 | js += "_ytrp_html5_video_last = _ytrp_html5_video;"; 169 | js += "function _ytrp_html5_video_ended() {"; 170 | { 171 | js += "_VideoEnabledWebView.notifyVideoEnd();"; // Must match Javascript interface name and method of VideoEnableWebView 172 | } 173 | js += "}"; 174 | js += "_ytrp_html5_video.addEventListener('ended', _ytrp_html5_video_ended);"; 175 | } 176 | js += "}"; 177 | webView.loadUrl(js); 178 | } 179 | } 180 | 181 | // Notify full-screen change 182 | if (toggledFullscreenCallback != null) 183 | { 184 | toggledFullscreenCallback.toggledFullscreen(true); 185 | } 186 | } 187 | } 188 | 189 | @Override @SuppressWarnings("deprecation") 190 | public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+ 191 | { 192 | onShowCustomView(view, callback); 193 | } 194 | 195 | @Override 196 | public void onHideCustomView() 197 | { 198 | // This method should be manually called on video end in all cases because it's not always called automatically. 199 | // This method must be manually called on back key press (from this class' onBackPressed() method). 200 | 201 | if (isVideoFullscreen) 202 | { 203 | // Hide the video view, remove it, and show the non-video view 204 | activityVideoView.setVisibility(View.INVISIBLE); 205 | activityVideoView.removeView(videoViewContainer); 206 | activityNonVideoView.setVisibility(View.VISIBLE); 207 | 208 | // Call back (only in API level <19, because in API level 19+ with chromium webview it crashes) 209 | if (videoViewCallback != null && !videoViewCallback.getClass().getName().contains(".chromium.")) 210 | { 211 | videoViewCallback.onCustomViewHidden(); 212 | } 213 | 214 | // Reset video related variables 215 | isVideoFullscreen = false; 216 | videoViewContainer = null; 217 | videoViewCallback = null; 218 | 219 | // Notify full-screen change 220 | if (toggledFullscreenCallback != null) 221 | { 222 | toggledFullscreenCallback.toggledFullscreen(false); 223 | } 224 | } 225 | } 226 | 227 | @Override 228 | public View getVideoLoadingProgressView() // Video will start loading 229 | { 230 | if (loadingView != null) 231 | { 232 | loadingView.setVisibility(View.VISIBLE); 233 | return loadingView; 234 | } 235 | else 236 | { 237 | return super.getVideoLoadingProgressView(); 238 | } 239 | } 240 | 241 | @Override 242 | public void onPrepared(MediaPlayer mp) // Video will start playing, only called in the case of android.widget.VideoView (typically API level <11) 243 | { 244 | if (loadingView != null) 245 | { 246 | loadingView.setVisibility(View.GONE); 247 | } 248 | } 249 | 250 | @Override 251 | public void onCompletion(MediaPlayer mp) // Video finished playing, only called in the case of android.widget.VideoView (typically API level <11) 252 | { 253 | onHideCustomView(); 254 | } 255 | 256 | @Override 257 | public boolean onError(MediaPlayer mp, int what, int extra) // Error while playing video, only called in the case of android.widget.VideoView (typically API level <11) 258 | { 259 | return false; // By returning false, onCompletion() will be called 260 | } 261 | 262 | /** 263 | * Notifies the class that the back key has been pressed by the user. 264 | * This must be called from the Activity's onBackPressed(), and if it returns false, the activity itself should handle it. Otherwise don't do anything. 265 | * @return Returns true if the event was handled, and false if was not (video view is not visible) 266 | */ 267 | @SuppressWarnings("unused") 268 | public boolean onBackPressed() 269 | { 270 | if (isVideoFullscreen) 271 | { 272 | onHideCustomView(); 273 | return true; 274 | } 275 | else 276 | { 277 | return false; 278 | } 279 | } 280 | 281 | } 282 | -------------------------------------------------------------------------------- /app/src/main/java/name/cpr/VideoEnabledWebView.java: -------------------------------------------------------------------------------- 1 | package name.cpr; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.os.Handler; 6 | import android.os.Looper; 7 | import android.util.AttributeSet; 8 | import android.util.Log; 9 | import android.webkit.WebChromeClient; 10 | import android.webkit.WebView; 11 | 12 | import java.util.Map; 13 | 14 | /** 15 | * This class serves as a WebView to be used in conjunction with a VideoEnabledWebChromeClient. 16 | * It makes possible: 17 | * - To detect the HTML5 video ended event so that the VideoEnabledWebChromeClient can exit full-screen. 18 | * 19 | * Important notes: 20 | * - Javascript is enabled by default and must not be disabled with getSettings().setJavaScriptEnabled(false). 21 | * - setWebChromeClient() must be called before any loadData(), loadDataWithBaseURL() or loadUrl() method. 22 | * 23 | * @author Cristian Perez (http://cpr.name) 24 | * 25 | */ 26 | public class VideoEnabledWebView extends WebView 27 | { 28 | public class JavascriptInterface 29 | { 30 | @android.webkit.JavascriptInterface @SuppressWarnings("unused") 31 | public void notifyVideoEnd() // Must match Javascript interface method of VideoEnabledWebChromeClient 32 | { 33 | Log.d("___", "GOT IT"); 34 | // This code is not executed in the UI thread, so we must force that to happen 35 | new Handler(Looper.getMainLooper()).post(new Runnable() 36 | { 37 | @Override 38 | public void run() 39 | { 40 | if (videoEnabledWebChromeClient != null) 41 | { 42 | videoEnabledWebChromeClient.onHideCustomView(); 43 | } 44 | } 45 | }); 46 | } 47 | } 48 | 49 | private VideoEnabledWebChromeClient videoEnabledWebChromeClient; 50 | private boolean addedJavascriptInterface; 51 | 52 | @SuppressWarnings("unused") 53 | public VideoEnabledWebView(Context context) 54 | { 55 | super(context); 56 | addedJavascriptInterface = false; 57 | } 58 | 59 | @SuppressWarnings("unused") 60 | public VideoEnabledWebView(Context context, AttributeSet attrs) 61 | { 62 | super(context, attrs); 63 | addedJavascriptInterface = false; 64 | } 65 | 66 | @SuppressWarnings("unused") 67 | public VideoEnabledWebView(Context context, AttributeSet attrs, int defStyle) 68 | { 69 | super(context, attrs, defStyle); 70 | addedJavascriptInterface = false; 71 | } 72 | 73 | /** 74 | * Indicates if the video is being displayed using a custom view (typically full-screen) 75 | * @return true it the video is being displayed using a custom view (typically full-screen) 76 | */ 77 | @SuppressWarnings("unused") 78 | public boolean isVideoFullscreen() 79 | { 80 | return videoEnabledWebChromeClient != null && videoEnabledWebChromeClient.isVideoFullscreen(); 81 | } 82 | 83 | /** 84 | * Pass only a VideoEnabledWebChromeClient instance. 85 | */ 86 | @Override @SuppressLint("SetJavaScriptEnabled") 87 | public void setWebChromeClient(WebChromeClient client) 88 | { 89 | getSettings().setJavaScriptEnabled(true); 90 | 91 | if (client instanceof VideoEnabledWebChromeClient) 92 | { 93 | this.videoEnabledWebChromeClient = (VideoEnabledWebChromeClient) client; 94 | } 95 | 96 | super.setWebChromeClient(client); 97 | } 98 | 99 | @Override 100 | public void loadData(String data, String mimeType, String encoding) 101 | { 102 | addJavascriptInterface(); 103 | super.loadData(data, mimeType, encoding); 104 | } 105 | 106 | @Override 107 | public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) 108 | { 109 | addJavascriptInterface(); 110 | super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); 111 | } 112 | 113 | @Override 114 | public void loadUrl(String url) 115 | { 116 | addJavascriptInterface(); 117 | super.loadUrl(url); 118 | } 119 | 120 | @Override 121 | public void loadUrl(String url, Map additionalHttpHeaders) 122 | { 123 | addJavascriptInterface(); 124 | super.loadUrl(url, additionalHttpHeaders); 125 | } 126 | 127 | private void addJavascriptInterface() 128 | { 129 | if (!addedJavascriptInterface) 130 | { 131 | // Add javascript interface to be called when the video ends (must be done before page load) 132 | //noinspection all 133 | addJavascriptInterface(new JavascriptInterface(), "_VideoEnabledWebView"); // Must match Javascript interface name of VideoEnabledWebChromeClient 134 | 135 | addedJavascriptInterface = true; 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cprcrack/VideoEnabledWebView/1e110ee26a77585882d84d4b4d3f1d4bad94b8be/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cprcrack/VideoEnabledWebView/1e110ee26a77585882d84d4b4d3f1d4bad94b8be/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cprcrack/VideoEnabledWebView/1e110ee26a77585882d84d4b4d3f1d4bad94b8be/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cprcrack/VideoEnabledWebView/1e110ee26a77585882d84d4b4d3f1d4bad94b8be/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_example.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 19 | 20 | 21 | 25 | 26 | 30 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /app/src/main/res/layout/view_loading_video.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | 13 | 19 | 20 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | VideoEnabledWebView 5 | Loading video… 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.3.3' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Settings specified in this file will override any Gradle settings 5 | # configured through the IDE. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cprcrack/VideoEnabledWebView/1e110ee26a77585882d84d4b4d3f1d4bad94b8be/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 16 21:46:15 PDT 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------