6

YouTube Video not playing in WebView.

It my first app ,I Want to do a webview. When I open YouTube the video not playing, is loading but not playing. Is loading all the time. Thank you so much for helping.

Java:

public class MainActivity extends Activity {

    private WebView mWebView;  

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

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.google.com");
        mWebView.setWebViewClient(new HelloWebViewClient());

    }

private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url)
        {
        webview.loadUrl(url);
        return true;
    }}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
        {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }   }

Xml:

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>
omer341
  • 467
  • 2
  • 8
  • 12

2 Answers2

23

Seems like duplicate of play youtube video in WebView and YouTube Video not playing in WebView - Android

To make it work via WebView, I used the following two steps (version 4.2.2/Nexus 4):

  1. On shouldOverrideUrlLoading I added webview.setWebChromeClient(new WebChromeClient());

  2. In AndroidManifest.xml for activity tag I added android:hardwareAccelerated="true"

AndroidManifest.xml should also contain Internet permission.

While exact steps with playing video via WebView can be specific to device and Android version, there are also other alternatives to WebView, like VideoView or using Youtube Android Player API.

EDIT1

As for pause and full screen, this is actually a second link I mentioned in the beginning. To make it easier, I am posting code that worked on my Nexus.

  1. In activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
     tools:context=".MainActivity" >
    
    <FrameLayout
              android:id="@+id/fullscreen_custom_content"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#FF000000"/>
    
    <LinearLayout 
              android:id="@+id/linearlayout"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent"> 
    
         <WebView
               android:id="@+id/webView"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent" />
    
    </LinearLayout>
    </RelativeLayout>
    
  2. In MainActivity class:

    public class MainActivity extends Activity {
    
    private WebView mWebView;  
    private LinearLayout mContentView;
    private FrameLayout mCustomViewContainer;
    private WebChromeClient.CustomViewCallback mCustomViewCallback;
    FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mContentView = (LinearLayout) findViewById(R.id.linearlayout);
        mWebView = (WebView) findViewById(R.id.webView);
        mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
    
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
    
        mWebView.loadUrl("http://www.google.com");
        mWebView.setWebViewClient(new HelloWebViewClient());
    
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    
    
    private class HelloWebViewClient extends WebViewClient  {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webview, String url)
        {
            webview.setWebChromeClient(new WebChromeClient() {
    
                private View mCustomView;
    
                 @Override
                public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
                {
                    // if a view already exists then immediately terminate the new one
                    if (mCustomView != null)
                    {
                        callback.onCustomViewHidden();
                        return;
                    }
    
                    // Add the custom view to its container.
                    mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
                    mCustomView = view;
                    mCustomViewCallback = callback;
    
                    // hide main browser view
                    mContentView.setVisibility(View.GONE);
    
                    // Finally show the custom view container.
                    mCustomViewContainer.setVisibility(View.VISIBLE);
                    mCustomViewContainer.bringToFront();
                }
    
            }); 
    
          webview.loadUrl(url);
    
          return true;
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
        {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    
    } 
    }
    

EDIT2 - adding back button support

public class MainActivity extends Activity {

private WebView mWebView;  
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.WRAP_CONTENT,
        ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);

private WebChromeClient mWebChromeClient;

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

    mContentView = (LinearLayout) findViewById(R.id.linearlayout);
    mWebView = (WebView) findViewById(R.id.webView);
    mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);

    mWebChromeClient = new WebChromeClient() {


         @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
        {
            // if a view already exists then immediately terminate the new one
            if (mCustomView != null)
            {
                callback.onCustomViewHidden();
                return;
            }

            // Add the custom view to its container.
            mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
            mCustomView = view;
            mCustomViewCallback = callback;

            // hide main browser view
            mContentView.setVisibility(View.GONE);

            // Finally show the custom view container.
            mCustomViewContainer.setVisibility(View.VISIBLE);
            mCustomViewContainer.bringToFront();
        }

         @Override
         public void onHideCustomView()
         {
             if (mCustomView == null)
                 return;

             // 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);
         } 
    };

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setPluginState(WebSettings.PluginState.ON);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);

    mWebView.loadUrl("http://www.google.com");
    mWebView.setWebViewClient(new HelloWebViewClient());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



private class HelloWebViewClient extends WebViewClient  {

    @Override
    public boolean shouldOverrideUrlLoading(WebView webview, String url)
    {
        webview.setWebChromeClient(mWebChromeClient);   
        webview.loadUrl(url);

      return true;
    }
}

@Override
protected void onStop() {

    super.onStop();
    if (mCustomView != null)
    {
        if (mCustomViewCallback != null)
            mCustomViewCallback.onCustomViewHidden();
        mCustomView = null;
    }

}

@Override
public void onBackPressed() {

    super.onBackPressed();
     if (mCustomView != null)
     {
         mWebChromeClient.onHideCustomView();
     } else
     {
         finish();
     }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
    {
        mWebView.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);

}   
}
Community
  • 1
  • 1
Alex P
  • 1,721
  • 1
  • 17
  • 18
  • 1
    @omer341 On which Android version you are trying to run it or emulate it? What have you tried ? Was the addition of `webview.setWebChromeClient(new WebChromeClient() {});` and hardware acceleration tag not useful for your case? – Alex P Jul 18 '13 at 11:56
  • 1
    I am trying to run it on my tablet On Android version 4.1.2. – omer341 Jul 18 '13 at 13:01
  • @omer341 I tried couple of steps above (added to answer) for my Nexus 4 and it did work. Have you tried exactly these steps? – Alex P Jul 18 '13 at 20:00
  • But after I press pause the video, it went black, and the video can not be full screen. – omer341 Jul 19 '13 at 05:52
  • @omer341 You can try the edit I posted above. And if it will hopefully work, you can override/implement additional stuff. – Alex P Jul 19 '13 at 22:12
  • Thanks a lot, but I Have one more error "linearlayout cannot be resolved or is not a field". – omer341 Jul 20 '13 at 06:52
  • @omer341 `linearlayout` is an id of LinearLayout in `activity_main.xml` in `layout` directory. Make sure that there is no typo in XML and it actually appears in that XML. – Alex P Jul 20 '13 at 08:01
  • Yes but I have an error in xml "The markup in the document following the root element must be well-formed." – omer341 Jul 20 '13 at 10:28
  • @omer341 I posted full content of my `activity_main.xml` with the header which is usually generated. – Alex P Jul 20 '13 at 10:48
  • Sorry, I can't to exit from the full screen. And it crashed when I back with the back button. Thank you very much for the help. – omer341 Jul 20 '13 at 12:04
  • @omer341 I have posted another edit with back button support, which should solve also exit from full screen (via back). For further questions, please open a new question in SO, and summarise what have you tried. Plus, start digging the code and stay with the problem a bit longer before you ask, i.e. try to solve it. – Alex P Jul 20 '13 at 13:28
  • 1
    Alex, If you could make this sample into a public project on BitBucket, it would be very helpful... it is hard to follow the bread crumbs, and this is apparently somewhat tricky matter on Android. – TacB0sS Oct 23 '13 at 21:17
  • Really quite a nice answer, unfortunately in my case (was using a fragment, attaching and detaching it to an activity) the `WebChromeClient`'s methods get called just on its first creation, while on subsequent creations they are not invoked at all. Wasn't able to understand why, just switched to an `Intent` for an external application to do the movie playing job instead. – Giulio Piancastelli Dec 19 '13 at 15:33
0

Adding webchrome client solves the issue,

web = (WebView) vi.findViewById(R.id.offer_webView1);

        web.loadUrl(getResources().getString(R.string.videolink));

        web.getSettings().setJavaScriptEnabled(true);
        // web.getSettings().setDomStorageEnabled(true);

        web.getSettings().setAllowContentAccess(true);
        WebSettings webSettings = web.getSettings();
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        web.canGoBack();
        web.setWebChromeClient(new WebChromeClient() {});
arun-r
  • 3,104
  • 2
  • 22
  • 20