[android] Playing HTML5 video on fullscreen in android webview

Well, I've been searching few days already, how to display HTML5 video in full-screen mode on android WebView.

I managed to play HTML5 videos on my webview. Problems are arising when displaying video in fullscreen mode.

As I figured out, android has two ways of handling the < video > tag:

  1. On android versions <= 2.3.3, the onShowCustomView method is fired, and I can have the VideoView instance, and set listeners when the video completes, set controllers etc. So far so good.

  2. On ICS (and probably 3.0 and above), it looks like the < video > is handled in different way. When the HTML5 video is played the onShowCustomView isn't being called on normal mode - it looks like there is an internal business inside the WebView that plays the video, and all the controls that are defined in the < video > tag are shown - I can't access it in any way. Actually, if the video is played in normal mode this is OK because the controls are there and are working.

That led me to the big problem: when displaying the video in full screen mode the onShowCustomView is being called - but on ICS the "view" parameter isn't an instance of VideoView.

I managed to find out that the instance is of VideoSurfaceView, a private inner class of HTML5VideoFullScreen class. The only way we can access this inner-class is via reflection.

After looking at GrepCode for this class, I learnt that unlike VideoView, the HTML5VideoFullScreen$VideoSurfaceView doesn't hold a MediaPlayer instance that I can listen to its events or access its controls. The only thing I can do is take this VideoSurfaceView as it is and put it inside a full-screen-layout without controlling it.

Bottom line - When displaying video in full-screen, I don't know when the video ends, its controls aren't shown - this is pretty sad. I can't get the trigger for closing the full-screen.

I tried few unsuccessful workarounds:

  1. Reflection: I tried to reach the HTML5VideoFullScreen instance, which holds a MediaPlayer member, from the inner-class VideoSurfaceView. I didn't manage to get it, I'm not sure this is possible (ViewSurfaceView doesn't hold its owner's instance).

  2. Register for the video events via Javascript (onended, for example), and handle what I need back in JAVA via JavascriptInterface: I found this solution isn't reliable because while doing this I encountered another problem: the < video > tag can be nested in an . The iframe source isn't mine and I can't get its content (getElementById or getElementsByTagName[i] are nulls) - which means, I can't reach the < video > element inside the iframe.

I'm still searching for a solution, very little is written about this issue. Did anyone manage to solve it? Help would be much appreciated!

VideoView class: Here (has MediaPlayer)

HTML5VideoFullScreen$VideoSurfaceView class: Here (doesn't have MediaPlayer)

This question is related to android android-webview html5-video

The answer is


Thank you so much for that class, Cristian.

I made a minor tweak to it so that the custom loading view is optional, like so:

  @Override
    public View getVideoLoadingProgressView() // Video will start loading, only called in the case of VideoView (typically API level 10-)
    {
        if (loadingView == null)
        {
            return super.getVideoLoadingProgressView();
        }
        else
        {
            loadingView.setVisibility(View.VISIBLE);
            return loadingView;
        }
    }

I also added a new constructor that just takes two parameters. Anyway, just a minor simplification if you don't need the loading view. Thanks again for providing this.


It seems that in lollipop and up (or maybe just a different WebView Version) that calling cprcrack's onHideCustomView() method does not work. It works if it is called from the exit fullscreen button but when you specifically call the method it will only exit fullscreen but the webView stays blank. A way around it is to simply add these lines of code to onHideCustomView():

String js = "javascript:";
js += "var _ytrp_html5_video = document.getElementsByTagName('video')[0];";
js += "_ytrp_html5_video.webkitExitFullscreen();";
webView.loadUrl(js);

This will notify the webView that fullscreen has exited.


Just set
mWebView.setWebChromeClient(new WebChromeClient());

and video plays as normally wont need any custom view.


Tested on Android 9.0 version

None of the answers worked for me . This is the final thing worked

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mWebView = (WebView) findViewById(R.id.webView);


        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyChrome());
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

       if (savedInstanceState == null) {
          mWebView.loadUrl("https://www.youtube.com/");
       }

    }


    private class MyChrome extends WebChromeClient {

        private View mCustomView;
        private WebChromeClient.CustomViewCallback mCustomViewCallback;
        protected FrameLayout mFullscreenContainer;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        MyChrome() {}

        public Bitmap getDefaultVideoPoster()
        {
            if (mCustomView == null) {
                return null;
            }
            return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
        }

        public void onHideCustomView()
        {
            ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
            this.mCustomView = null;
            getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
            setRequestedOrientation(this.mOriginalOrientation);
            this.mCustomViewCallback.onCustomViewHidden();
            this.mCustomViewCallback = null;
        }

        public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
        {
            if (this.mCustomView != null)
            {
                onHideCustomView();
                return;
            }
            this.mCustomView = paramView;
            this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            this.mOriginalOrientation = getRequestedOrientation();
            this.mCustomViewCallback = paramCustomViewCallback;
            ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
            getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
}

In AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:configChanges="orientation|screenSize" />

Source Monster Techno


Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView will get it working on API level 21+

if (Build.VERSION.SDK_INT >= 21) {
      videoViewContainer.setBackgroundColor(Color.BLACK);
      ((ViewGroup) webView.getParent()).addView(videoViewContainer);
      webView.scrollTo(0,0);  // centers full screen view 
} else {
      activityNonVideoView.setVisibility(View.INVISIBLE);
      ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
      activityVideoView.addView(videoViewContainer,vg);
      activityVideoView.setVisibility(View.VISIBLE);
}

You will also need to reflect the changes in onHideCustomView


Edit: please see my other answer, as you probably don't need this now.

As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".

This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:

@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);

@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);

Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild

Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.

So, now you could set the onCompletion listener of the MediaPlayer instance like this:

OnCompletionListener ocl = new OnCompletionListener()
{
    @Override
    public void onCompletion(MediaPlayer mp)
    {
        // Do stuff
    }
};

Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);

The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.


This is great. But if you want your website links to open in the app itself, add this code in your ExampleActivity.java:

webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().endsWith("yourwebsite.com")) {
                return false;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.getContext().startActivity(intent);
            return true;
        }
    });

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-webview

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? Embed Youtube video inside an Android app Android WebView not loading URL Playing HTML5 video on fullscreen in android webview How to load html string in a webview? Android webview launches browser when calling loadurl Add custom headers to WebView resource requests - android Android WebView not loading an HTTPS URL How to load external webpage in WebView

Examples related to html5-video

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66? In Chrome 55, prevent showing Download button for HTML 5 video HTML 5 Video "autoplay" not automatically starting in CHROME How to open .mov format video in HTML video Tag? What is a blob URL and why it is used? .mp4 file not playing in chrome HTML5 video won't play in Chrome only use video as background for div HTML5 Video tag not working in Safari , iPhone and iPad Video 100% width and height