46

I am tying to play YouTube video in WebView, WebView showing first look of video with play button, But after click on play button start progress bar and after 2-3 seconds stop progress bar and screen blank with black color.

Image1: Video first look with play button

Image2: After click on play button screen goes blank.

Please! help me why video not starting.

IMAGE:1 This is first look of web view

IMAGE:2 enter image description here

This is my source code to play YouTubeVideo in webview.. Please help me ...

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    WebView wv = (WebView) findViewById(R.id.webView1);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setPluginsEnabled(true);
    final String mimeType = "text/html";
    final String encoding = "UTF-8";
    String html = getHTML();
    wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
}

public String getHTML() {
    String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
            + "J2fB5XWj6IE"
            + "?fs=0\" frameborder=\"0\">\n"
            + "</iframe>\n";
    return html;
}
4castle
  • 32,613
  • 11
  • 69
  • 106
Ranjitsingh Chandel
  • 1,479
  • 6
  • 19
  • 33

11 Answers11

72

Add these lines before loading HTML content to your WebView.

wv.setWebChromeClient(new WebChromeClient() {
});

From the documentation:

In order to support inline HTML5 video in your application, you need to have hardware acceleration turned on, and set a WebChromeClient. For full screen support, implementations of onShowCustomView(View, WebChromeClient.CustomViewCallback) and onHideCustomView() are required, getVideoLoadingProgressView() is optional.

Łukasz Sromek
  • 3,637
  • 3
  • 30
  • 43
  • Please give your comments here also http://stackoverflow.com/questions/18533678/playing-youtube-videos-smoothly-in-web-view – anshul Sep 03 '13 at 13:07
  • 1
    still from the doc, about onShowCustomView() : This method was deprecated in API level 18. This method supports the obsolete plugin mechanism, and will not be invoked in future – elgui Sep 13 '13 at 14:46
  • i tried ur code but its not working here is full code https://gist.github.com/engr-erum/3135924c188f3fe4867270bb7b8b3f0a – Erum Oct 13 '17 at 04:30
  • 1
    Not working. It still show blank screen but audio is playing. Looking for help. – brijexecon Jun 01 '18 at 07:35
18

The following code is needed to show the video player that is started by the web core framework. The key to the entire flow is that the VideoView is passed back to the WebChromeClient and you need to attach that view to your view hierarchy.

I have assembled it through reviewing the Browser source code available as part of the AOSP.

This code references 4 Views which may not be obvious. The view hierarchy is:

  • FrameLayout mContentView (root)
  • WebView mWebView (child of mContentView)
  • FrameLAyout mCustomViewContainer (child of mContentView)
  • View mCustomView (child of mCustomViewContainer)

The views are configured as part of setting up the container activity.

<FrameLayout
    android:id="@+id/fullscreen_custom_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF000000"/>

    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <WebView
            android:id="@+id/webView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </FrameLayout>
</FrameLayout>

In your Activities onCreate:

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

Register a WebChromeClient with mWebView. That client should override the following 2 - 4 methods:

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

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

public Bitmap getDefaultVideoPoster()
{
    if (mDefaultVideoPoster == null)
    {
        mDefaultVideoPoster = BitmapFactory.decodeResource(getResources(), R.drawable.default_video_poster);
    }
    return mDefaultVideoPoster;
}

public View getVideoLoadingProgressView()
{
    if (mVideoProgressView == null)
    {
        LayoutInflater inflater = LayoutInflater.from(this);
        mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
    }
    return mVideoProgressView;
}

You may also want to add activity life-cycle bindings like:

@Override
protected void onStop()
{
    super.onStop();
    if (mCustomView != null)
    {
        if (mCustomViewCallback != null)
            mCustomViewCallback.onCustomViewHidden();
        mCustomView = null;
    }
}

@Override
public void onBackPressed()
{
    if (mCustomView != null)
    {
        onHideCustomView();
    } else
    {
        finish();
    }
}

To your activity to make the video hide when the activity is stopped or the back button is pressed.

Nelson
  • 27
  • 6
Nick Campion
  • 10,479
  • 3
  • 44
  • 58
  • 11
    could you please provide a clean code? There are so many mistakes? For e.g. where is the mCustomView? What is COVER_SCREEN_GRAVITY_CENTER? – Winston Apr 13 '13 at 13:09
  • mCustomView is described in the body of the answer. COVER_SCREEN_GRAVITY_CENTER is a LayoutParameter with bounds set to MATCH_PARENT and gravity set to CENTER. I figured that was obvious, sorry. – Nick Campion Apr 14 '13 at 01:22
  • @NickCampion don't understand please clear about COVER_SCREEN_GRAVITY_CENTER – Md Imran Choudhury Aug 21 '18 at 09:43
12

Add webview.setWebChromeClient(new WebChromeClient()); and to enable plugins for your video add:

if (Build.VERSION.SDK_INT < 8) {
            webview.getSettings().setPluginsEnabled(true);
        } else {
            webview.getSettings().setPluginState(PluginState.ON);
        }
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Siddharth_Vyas
  • 9,972
  • 10
  • 39
  • 69
5

There is some problem with the youtbe videos streamed on the mobile devices. If you directly try to load the URL in the web view and run it then the video won't play. One difficult way of solving this problem is to stream the video in the video view. I have not tried this but this can be done.
Other way to play the youtube videos, I will call this the easier way is to change the user agent in the web view settings from mobile device to a desktop. User agent indicates the type of device on which the youtube video will run and accordingly that kind of web page is sent by the server. This way the youtube video can be streamed and played. Here is how you can do this:

public static final int USER_MOBILE  = 0;
public static final int USER_DESKTOP = 1;
wv.getSettings().setUserAgent(USER_DESKTOP);   // 1 is for the desktop
karn
  • 5,963
  • 3
  • 22
  • 29
2

I copied the askers code and it worked for me.... i think u have to install flash payer.. di u?? and did u add internet permission???

btw my code is here...

package com.example.youtube;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsoluteLayout;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;


import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends Activity{


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

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);




            setContentView(R.layout.activity_main);


final ProgressBar Pbar;

Pbar = (ProgressBar) findViewById(R.id.pB4);
WebView wv = (WebView) findViewById(R.id.webVie1);
//wv.setWebViewClient(new Callback());
WebSettings webSettings = wv.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
//wv.setBackgroundColor(0x919191);
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML();
wv.loadDataWithBaseURL("", html, mimeType, encoding, "");




final Activity activity = this;

wv.setWebChromeClient(new WebChromeClient() {
       public void onProgressChanged(WebView view, int progress) {
         // Activities and WebViews measure progress with different scales.
         // The progress meter will automatically disappear when we reach 100%

         activity.setProgress(progress * 100);
         {
             if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
                 Pbar.setVisibility(ProgressBar.VISIBLE);

             }
             Pbar.setProgress(progress);
             if(progress == 100) {
                 Pbar.setVisibility(ProgressBar.GONE);

             }
          }
       }
     });
     wv.setWebViewClient(new WebViewClient() {
       public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
         Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_LONG).show();
       }
     });
     wv.setDownloadListener(new DownloadListener()
     {

        public void onDownloadStart(String url, String userAgent,String contentDisposition, String mimetype,long contentLength)
         {
             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

             startActivity(intent);   
         }


     });







}

    private String getHTML() {
        // TODO Auto-generated method stub
        String html1 = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
                + "J2fB5XWj6IE"
                + "?fs=0\" frameborder=\"0\">\n"
                + "</iframe>\n";
        return html1;
    }


  /*  public void onPause()
    {
        super.onPause();
        System.exit(0);
    }*/




}

layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

<LinearLayout
    android:id="@+id/page_buttons"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="horizontal" >


</LinearLayout>

<WebView
    android:id="@+id/webVie1"
    android:layout_width="316dp"
    android:layout_height="392dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
    android:layout_weight="0.99" />

<ProgressBar
    android:id="@+id/pB4"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"/> />
</LinearLayout>
1

Below works upto Android 10. Load a "WebView" in your Android Activity/ Fragment.

Check this for a working project.

private fun loadVideo(webView: WebView) {

    val videoUrl = "https://www.youtube.com/embed/5jJ-e278BFY"

    val embedString = "<iframe  src=\"$videoUrl\" frameborder=\"0\" allowfullscreen></iframe>"
    webView.webChromeClient = WebChromeClient()
    val webSettings = webView.settings
    webSettings.javaScriptEnabled = true
    webView.settings.loadWithOverviewMode = true

    var text = "<html><body style=\"text-align:justify;\">"
    text += embedString
    text += "</body></html>"
    webView.loadData(text, "text/html", "utf-8")
}

It uses the IFrame Player API. width (number) – The width of the video player. The default value is 640. height (number) – The height of the video player. The default value is 390. videoId (string) – The YouTube video ID that identifies the video that the player will load.

Below is the UI xml

 <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/youtubeVideoFrameSubText" />
Mayuri Khinvasara
  • 1,437
  • 1
  • 16
  • 12
0

Why do you want to play you tube video in webview? You can play it by using this intent

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(stringUrl)));

Otherwise if you want to play it in webView follow this link

http://www.stackoverflow.com/questions/9565533/android-how-to-play-youtube-video-in-webview?rq=1

dokkaebi
  • 9,004
  • 3
  • 42
  • 60
sai
  • 2,562
  • 8
  • 31
  • 46
0

my webview had javascript enabled but removing made the video work

        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Vihaan Verma
  • 12,815
  • 19
  • 97
  • 126
0
myWebView.getSettings().setDomStorageEnabled(true);
saeedmpt
  • 144
  • 1
  • 7
0

For me the issue was setting cleartextTrafficPermitted to false. For some reason, setting this wouldn't play YouTube video at URL http://www.youtube-nocookie.com/embed/%s, where %s is the ID of the YouTube video.

The solution was to include following in the network_security_config.xml file.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="false">
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">youtube-nocookie.com</domain>
    </domain-config>
</network-security-config>

The network_security_config.xml file is referenced in AndroidManifest.xml, <application> tag and networkSecurityConfig parameter.

Hope this saves someone's time!

Dhunju_likes_to_Learn
  • 1,201
  • 1
  • 16
  • 25
-3

Try This one

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(stringUrl)));