32

I have an android webview that loads a wordpress blog. Some blog posts contain youtube videos which I would like the user to be able to make full screen if they wish. The problem is the HTML5 full screen button does nothing when clicked but freeze up the view. Any ideas?

wilxjcherokee
  • 573
  • 2
  • 8
  • 17

3 Answers3

51

This is something I've spent the last day or so tearing my hair out over. Based on various bits of code from around the web I've managed to get it working.

First, you need to create a custom WebChromeClient class, which implements the onShowCustomView and onHideCustomView methods.

private class MyWebChromeClient extends WebChromeClient {
    FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT);

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (mCustomView != null) {
            callback.onCustomViewHidden();
            return;
        }
        mContentView = (RelativeLayout) findViewById(R.id.activity_main);
        mContentView.setVisibility(View.GONE);
        mCustomViewContainer = new FrameLayout(MainActivity.this);
        mCustomViewContainer.setLayoutParams(LayoutParameters);
        mCustomViewContainer.setBackgroundResource(android.R.color.black);
        view.setLayoutParams(LayoutParameters);
        mCustomViewContainer.addView(view);
        mCustomView = view;
        mCustomViewCallback = callback;
        mCustomViewContainer.setVisibility(View.VISIBLE);
        setContentView(mCustomViewContainer);
    }

    @Override
    public void onHideCustomView() {
        if (mCustomView == null) {
            return;
        } else {
            // Hide the custom view.  
            mCustomView.setVisibility(View.GONE);
            // Remove the custom view from its container.  
            mCustomViewContainer.removeView(mCustomView);
            mCustomView = null;
            mCustomViewContainer.setVisibility(View.GONE);
            mCustomViewCallback.onCustomViewHidden();
            // Show the content view.  
            mContentView.setVisibility(View.VISIBLE);
            setContentView(mContentView);
        }
    }
}

Basically, what is happening here is when the full screen button gets pressed, we're creating a new view to hold the video and hiding the main view. And then when full screen is closed, we do the opposite - get rid of the new view and display the original view.

You'll need to also add all those properties to your activity class:

private MyWebChromeClient mWebChromeClient = null;
private View mCustomView;
private RelativeLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;

And you probably want to make it close the fullscreen video when the back button is pressed:

@Override
public void onBackPressed() {
    if (mCustomViewContainer != null)
        mWebChromeClient.onHideCustomView();
    else if (myWebView.canGoBack())
        myWebView.goBack();
    else
        super.onBackPressed();
}

Then it's just a matter of using your new class when you create your webview:

myWebView = (WebView) findViewById(R.id.webView1);
mWebChromeClient = new WMWebChromeClient();
myWebView.setWebChromeClient(mWebChromeClient);

This works for me on Android 4.x. Not sure about earlier versions as my app isn't targeting them.

I found these links particularly useful: WebView and HTML5 <video> and http://code.google.com/p/html5webview/source/browse/trunk/HTML5WebView/src/org/itri/html5webview/HTML5WebView.java

Community
  • 1
  • 1
Mark Parnell
  • 9,175
  • 9
  • 31
  • 36
  • In your code sample, what is mContentView in the context of a view for full screen? I imagine it's some kind of layout you've inflated, but how did you make it fullscreen. Can you post the XML for your mContentView object? – Andrew Weir Apr 24 '13 at 08:28
  • `mContentView` is the main activity view, which gets hidden when the video is made fullscreen. I'm not making the video fullscreen automatically though; the user does that (if they want to) when watching the video. – Mark Parnell Apr 25 '13 at 22:34
  • @MarkParnell Please give your comments here also http://stackoverflow.com/questions/18533678/playing-youtube-videos-smoothly-in-web-view – anshul Sep 03 '13 at 13:10
  • @MarkParnell Thanks for your solution but I am getting error "Attempt to call getDuration without a valid media player" also there is error ( -38,0). Any idea? – unknown Jul 30 '14 at 14:17
  • after exiting the activity, I see endless `V/MediaPlayer(15998): isPlaying: 0` messages. Why is mediaplayer still active when the activity is exited ? – Someone Somewhere Oct 21 '14 at 22:26
  • another use case: pressing the power button when the video is playing in full screen. This really F's things up ! – Someone Somewhere Oct 21 '14 at 22:52
  • How to handle orientation change? – Sachin Thampan Jun 12 '16 at 16:24
  • Great solution and at least I came a little bit closer to the required functionality (youtube video playback when no native app is installed). I have my OnShow/OnHide handlers called but I'm getting black while screen (even though the background is black). I can hear the video in full mode but couldn't see it. Any suggestions? – Mando Jul 21 '16 at 01:14
  • I have used this code in fragment. in Onhideview is forces me to remove parent views child view. This will remove the toolbar as well. How to do this ? @MarkParnell – madhuri H R Jun 16 '17 at 07:08
1

Thanks to @Mark Parnell for his response, but he is doing it in hard way with heavy UI changes, maybe this way is cleaner and more understandable:

When fullscreen button clicked, chrome client gives us fullscreen view and then we should add it to our activity view :

Define this variable global to hold fullscreen view reference in our activity:

public class MyAmazingActivity extends AppCompatActivity {
    private View fullscreenView;
    //...
}

Then web chrome client will notify us about showing and hiding fullscreen view in onShowCustomView and onHideCustomView methods:

WebChromeClient webChromeClient = new WebChromeClient() {

            private ViewGroup rootView;
            private WebChromeClient.CustomViewCallback customViewCallback;

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {

                //Destroy full screen view if already exists
                if (fullscreenView != null) {
                    callback.onCustomViewHidden();
                    return;
                }

                //Layout params to fit fullscreen view in our activity
                ViewGroup.LayoutParams layoutParams = 
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT);
                //Catch root of current activity to add fullscreen view
                rootView = (ViewGroup) WebViewBaseActivity.this.webView.getRootView();
                
                //Store full screen view, we need it to destroy it out of scope
                fullscreenView = view;

                customViewCallback = callback;
                rootView.addView(fullscreenView, layoutParams);
            }

            @Override
            public void onHideCustomView() {
                //Make sure fullscreen view exists
                if (fullscreenView != null) {
                    
                    //Remove fullscreen view from activity root view
                    rootView.removeView(fullscreenView);
                    fullscreenView = null;

                    //Tell browser we did remove fullscreen view
                    customViewCallback.onCustomViewHidden();
                }
            }

        };

And finally removing fullscreen view when back pressed(User expects this behaviour):

@Override
public void onBackPressed() {
    if (fullscreenView != null) {
        webChromeClient.onHideCustomView();
    }
}       
Hossein
  • 797
  • 1
  • 8
  • 24
0

You can start an external YouTube app when you will cath video info URLif it is not important to show YouTube video directly in application.

To catch video info URL You need to owerride onLoadResource method:

new WebViewClient() {

    @Override
    public void onLoadResource(WebView view, String url) {

        if (url.startsWith("http://www.youtube.com/get_video_info?")) {
            try {
                String path = url.replace("http://www.youtube.com/get_video_info?", "");

                String[] parqamValuePairs = path.split("&");

                String videoId = null;

                for (String pair : parqamValuePairs) {
                    if (pair.startsWith("video_id")) {
                        videoId = pair.split("=")[1];
                        break;
                    }
                }

                if(videoId != null){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                            .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));
                    needRefresh = true;

                    return;
                }
            } catch (Exception ex) {
            }
        } else {
            super.onLoadResource(view, url);
        }
    }
}
Roman Black
  • 3,501
  • 1
  • 22
  • 31
  • Nice code, but when i press on video it also start playing in webview, how can i Cancel that? – KiKo Oct 13 '14 at 11:47
  • You can call WebView.reload(). But You can implement fullscreen video directly in app if You dont need to start foreign app. – Roman Black Oct 15 '14 at 09:09