Nikita Gupta
Nikita Gupta

Reputation: 113

Auto play video in webview

I am new in android and I am displaying a news link in a webview. News link contains a video. Problem is that, After opening a link i have to click on video then video is playing but i want that video should be play automatically.

Thanks in advance.

My code is:

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setPluginState(PluginState.ON);         

myWebView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) { web.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
    });

myWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("http://aajtak.intoday.in/livetv.html");  

Upvotes: 11

Views: 24752

Answers (5)

Andre Silva
Andre Silva

Reputation: 11

Just make your webview thinking he is running in PC instead mobile Insert this os MainActivity file

webView.getSettings().setUserAgentString("1");//for desktop 1 or mobile 0.

Upvotes: 1

Priyanka G
Priyanka G

Reputation: 191

This works for me.

webView.getSettings().setMediaPlaybackRequiresUserGesture(false);

using above, after opening a link no need to click on video, the video is playing automatically.

Upvotes: 17

XuLu
XuLu

Reputation: 89

video on webview didn't support 'autoplay'. so we shoud start video by hand: android:

@Override
public void onPageFinished(WebView view, String url) {
 super.onPageFinished(view, url);
 view.loadUrl("javascript:onPageFinished();"); 
}

JS:

function onPageFinished() {
    var video = document.getElementById("video");
    video.play();
}

Upvotes: 3

Harsh Shah
Harsh Shah

Reputation: 331

myWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);

https://developer.android.com/reference/android/webkit/WebSettings.html#setMediaPlaybackRequiresUserGesture(boolean)

Note: Only for API level 17 and above.

Upvotes: 32

Ahmad Tn
Ahmad Tn

Reputation: 390

myWebView.setWebViewClient(new WebViewClient() {
  public void onPageFinished(WebView view, String url) {web.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});

You should implement loadUrl on the WebView... Simply replace web.loadUrl with view.loadUrl and it should work just fine

Upvotes: 2

Related Questions