Unable to play video using WebView - android

I'd like to play a video using WebView capabilities.
Currently I'm able to play the following html in all browsers I've tested (Chrome, Chrome for Android, Navegator for Android). Unfortunately, I can not get it playing inside my own application using a WebView: the player's controls are shown, but clicking at play button make the seek bar goes to the end and a progress circle takes place and never ends.
Here are the relevant code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/www/index.html");
}
index.html:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>video1</title>
</head>
<body>
<video id="video" controls height="240" width="360">
<source src="index.files/html5video/video1.m4v">
</video>
<script type="text/javascript">
var vid=document.getElementById('video');
vid.addEventListene('click', function () {
vid.play();
}, false);
</script>
</body>
You can rely that all files are placed in the right place.

I know this is an old post, but I was having the same issue on my Galaxy S3. I solved it with this :
webView.SetWebChromeClient (new WebChromeClient ());
It worked just fine on Nexus 7 without this line, but on Galaxy S3 for some reason it just spun the loading circle forever.
NOTE: I also have these set:
webView.Settings.PluginsEnabled = true;
webView.Settings.JavaScriptEnabled = true;
webView.Settings.SetPluginState (WebSettings.PluginState.On);
webView.SetWebViewClient (new WebViewClient ());

I had the same problem, none of solutions found at others helped me. I have tried many different ways to solve this, but I didn't managed. So, my solution was to display a thumb instead of video, this thumb was an image linking to video source and when this thumb pressed, the video starts in Android native video player. You could try this if didn't resolved it yet.
Later, I found this: https://code.google.com/p/googletv-android-samples/source/browse/#git%2FWebAppNativePlayback It works by playing video in webview as you want, but the problem is you can not control video controls from D-pad keyboard.
Hope you got a solution!

Related

Issue embedding YouTube HTML5 in Android App

So I've searched around on SO a fair bit today and have made significant progress, but now I'm having an issue that I haven't seen pop up anywhere. I've embedded a YouTube video into an HTML file using an iframe as such:
<body>
<div align="center">
<iframe class="youtube-player" type="text/html" width="480" height="320"
src="http://www.youtube.com/embed/9DNAyD4ll6E?html5=1" frameborder="0">
</div>
</body>
and I'm displaying it in a WebView that I'm modifying in my activity like so:
WebView welcomeWebView = (WebView) findViewById(R.id.welcomeVideo);
welcomeWebView.setHorizontalScrollBarEnabled(false);
welcomeWebView.setVerticalScrollBarEnabled(false);
welcomeWebView.getSettings().setJavaScriptEnabled(true);
welcomeWebView.loadUrl("file:///android_asset/welcome.html");
The issue I'm having is that the still image display and controls show up, but when I click on play I'm presented with a gray screen that has a film strip and play icon in it. Here's the screen shots for the before/after for hitting play
http://www.ptrprograms.com/youtubeapp.png
http://www.ptrprograms.com/youtubeapp2.png
If anyone has seen this before or can point me in the right direction for displaying a video, I'd really appreciate it. Thank you!
EDIT: I also know that I can just use an intent to open it in a YouTube app, but my client (a non-profit that I'm donating this app to) is pretty specific about wanting it embedded into a page where we can have a textview with more information below it.
So I ditched the external asset for the webview and instead decided to load it in the activity itself, and it seems to work a lot better (it actually runs :))
WebView webView = (WebView) findViewById(R.id.welcomeVideo);
String play= "<html><body><div align=\"center\"> <iframe class=\"youtube-player\" type=\"text/html\" width=\"480\" height=\"320\" src=\"http://www.youtube.com/embed/9DNAyD4ll6E?rel=0\" frameborder=\"0\"></div></body></html>";
webView.setWebChromeClient(new WebChromeClient() {
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadData(play, "text/html", "utf-8");
webView.setBackgroundColor(0x00000000);

html5 video playlist android

I'm currently working on a app with some native and html5 features.
The streamed content will be loaded in a webview.
I need a html5 videoplayer with a playlist, autoplay and autorepeat(loop).
I have it working on my chrome webbrowser. But for some reason it wont work in the webview on android.
<video id="awesome_video" width="100%" height="100%" src="video/video.mp4" autoplay />
<script type="text/javascript">
var index = 1,
playlist = ["video/video.mp4", "video/video2.mp4"],
video = document.getElementById('awesome_video');
video.addEventListener('ended', rotate_video, false);
function rotate_video() {
video.setAttribute('src', playlist[index]);
video.load();
index++;
if (index >= playlist.length) { index = 0; }
}
</script>
On android it wont start automatically, and when I touch the screen to play it takes some time to buffer. But after that no video is shown.
I know a repeat function that works on android:
video.addEventListener('ended', function()
{
video.currentTime=0.1;
video.play();
}
In my android app i've already set my webview as chromeclient:
mWebView = (WebView) findViewById(R.id.wvMain);
mWebView.setWebChromeClient(new WebChromeClient());
I can get it working without playlist and autoplay(just a single video played repeatedly).
Hope anyone knows how to get this working on an android device, thx.

How to autoplay HTML5 mp4 video on Android?

I had developed a mobile page by asp.net to play mp4 video.
I know iOS had disabled the autoplay function to minimize user bandwidth, so how can i
autoplay HTML5 mp4 video on Android ?
I had already put autoplay in HTML5 code, but it doesn't work.
The following is my code:
<video autoplay controls id='video1' width='100%' poster='images/top_icon.png' webkitEnterFullscreen poster preload='true'>
<source src='http://192.xxx.xxx.xx/XXXXVM01.mp4' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2' >
</video>
Moreover, I had fixed the problem that user click on the image overlay can play the video.
Thanks Karthi
here are the code:
<script type="text/javascript">
$(document).ready(function() {
$("#video1").bind("click", function() {
var vid = $(this).get(0);
if (vid.paused) { vid.play(); }
else { vid.pause(); }
});
});
</script>
Thanks
Joe
You can add the 'muted' and 'autoplay' attributes together to enable autoplay for android devices.
e.g.
<video id="video" class="video" autoplay muted >
I used the following code:
// get the video
var video = document.querySelector('video');
// use the whole window and a *named function*
window.addEventListener('touchstart', function videoStart() {
video.play();
console.log('first touch');
// remove from the window and call the function we are removing
this.removeEventListener('touchstart', videoStart);
});
There doesn't seem to be a way to auto-start anymore.
This makes it so that the first time they touch the screen the video will play. It will also remove itself on first run so that you can avoid multiple listeners adding up.
Android actually has an API for this! The method is setMediaPlaybackRequiresUserGesture(). I found it after a lot of digging into video autoplay and a lot of attempted hacks from SO. Here's an example from blair vanderhoof:
package com.example.myProject;
import android.os.Bundle;
import org.apache.cordova.*;
import android.webkit.WebSettings;
public class myProject extends CordovaActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html");
WebSettings ws = super.appView.getSettings();
ws.setMediaPlaybackRequiresUserGesture(false);
}
}
I don't think autoplay works on Android, but getting a video to play can be annoyingly tricky. I suggest giving this article a read: Making HTML5 Video work on Android phones.
In Android 4.4 and above you can remove the need for a user gesture so long as the HTML5 Video component lives in your own WebView
webview.setWebChromeClient(new WebChromeClient());
webview.getSettings().setMediaPlaybackRequiresUserGesture(false);
To get the video to autoplay, you'd still need to add autoplay to the video element:
<video id='video' controls autoplay>
<source src='http://192.xxx.xxx.xx/XXXXVM01.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' >
</video>
Important Note: Be aware that if Google Chrome Data Saver is enabled in Chrome's settings, then Autoplay will be disabled.
Autoplay only works the second time through.
on android 4.1+ you have to have some kind of user event to get the first play() to work. Once that has happened then autostart works.
This is so that the user is acknowledging that they are using bandwidth.
There is another question that answers this .
Autostart html5 video using android 4 browser
similar to KNaito's answer, the following does the trick for me
function simulateClick() {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var cb = document.getElementById('player');
var canceled = !cb.dispatchEvent(event);
if (canceled) {
// A handler called preventDefault.
alert("canceled");
} else {
// None of the handlers called preventDefault.
alert("not canceled");
}
}
In Android 4.1 and 4.2, I use the following code.
evt.initMouseEvent( "click", true,true,window,0,0,0,0,0,false,false,false,false,0, true );
var v = document.getElementById("video");
v.dispatchEvent(evt);
where html is
<video id="video" src="sample.mp4" poster="image.jpg" controls></video>
This works well. But In Android 4.4, it does not work.
Here is a plugin for PhoneGap which solved the problem for me:
https://build.phonegap.com/plugins/1031
I simply included it in my config.xml
<video autoplay controls id='video1' width='100%' poster='images/top_icon.png' webkitEnterFullscreen poster preload='true'>
<source src='http://192.xxx.xxx.xx/XXXXVM01.mp4' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2' >
</video>
I simplified the Javascript to trigger the video to start.
var bg = document.getElementById ("bg");
function playbg() {
bg.play();
}
<video id="bg" style="min-width:100%; min-height:100%;" playsinline autoplay loop muted onload="playbg(); "><source src="Files/snow.mp4" type="video/mp4"></video>
</td></tr>
</table>
*"Files/snow.mp4" is just sample url
Can add muted tag.
<video autoplay muted>
<source src="video.webm" type="video/webm" />
<source src="video.mp4" type="video/mp4" />
</video>
reference https://developers.google.com/web/updates/2016/07/autoplay
don't use "mute" alone, use [muted]="true" for example following code:
<video id="videoPlayer" [muted]="true" autoplay playsinline loop style="width:100%; height: 100%;">
<source type="video/mp4" src="assets/Video/Home.mp4">
<source type="video/webm" src="assets/Video/Home.webm">
</video>
I test in more Android and ios
Chrome has disabled it. https://bugs.chromium.org/p/chromium/issues/detail?id=159336
Even the jQuery play() is blocked. They want user to initiate it so bandwidth can be saved.

Android webview cannot render youtube video embedded via iframe

This is about loading youtube videos using latest embedded format (iframe) inside a webview.
Example of the iframe embed format
<iframe width="637" height="358" src="http://www.youtube.com/embed/olC42gO-Ln4?fs=1&feature=oembed" frameborder="0" allowfullscreen=""></iframe>
Test the code on Android 2.3.3 & 3.2 devices (HTC Desire & Asus Transformer), the webview would only show a black rectangle.
I tried a similar embed from vimeo
<iframe src="http://player.vimeo.com/video/35693267" width="640" height="360" frameborder="0"></iframe>
In 2.3, video played correctly
In 3.2, a black rectangle flashed and disappeared, the iframe area is blank.
Finally if the old embed format (using the object tag) is used, the video is displayed properly inside the webview in both 2.3.3 & 3.2.
I have checked related questions and added
android:hardwareAccelerated="true"
in the application and/or activity tag but still no video in both 2.3 & 3.2 devices.
This is a big problem because more websites are now using the newest format (iframe) to embed their youtube videos. Android/Youtube Team, please take a look at this problem.
Android browsers are utterly buggy what comes to video playback and embedding. It simply does not work across devices. Trying to get it working is just waste of your time. My suggestion is that you don't try to include <iframe> but simply provide a thumbnail of the video which directly links to YouTube page or h264 file.
Earlier discussion, with a possible solution.
Google Reader-esque optimizing of WebViews on Android
If you want to play videos within your WebView you NEED to load the data with a base URL!
DONT do this:
mContentWebView.loadDataWithBaseURL(null, webViewContentString,
"text/html", "UTF-8", null);
DO THIS INSTEAD:
//veryVeryVery important for playing the videos!
mContentWebView.loadDataWithBaseURL(theBaseUrl, webViewConentString,
"text/html", "UTF-8", null);
The Base URL will be the something like the "original" url of what you are displaying in your WebView. So let's say you are making a news reader, the WebView's base url will be the url of the original story.
Good Luck!
Also remember to set up your WebView...Like so...
mContentWebView.setWebChromeClient(new WebChromeClient());
mContentWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mContentWebView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
mContentWebView.setWebViewClient(new WebViewClient());
mContentWebView.getSettings().setJavaScriptEnabled(true);
You need to have hardware acceleration turned on in the Manifest (only available on SDK 14 and above).
Ex. Hardware Acceleration On:
<application
android:name="com.example.app"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:hardwareAccelerated="true">
<!-- hardwareAccelerated requires SDK 14 -->
...
</application>
HTML5 Video support
In order to support inline HTML5 video in your application, you need to have hardware acceleration turned on, and set a WebChromeClient.
http://developer.android.com/reference/android/webkit/WebView.html
(Hope it help someone)
This worked for me- the code opens youtube site and can play its videos inside WebView:
mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://www.youtube.com/\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mWebView.loadData(frameVideo, "text/html", "utf-8");
mWebView.loadUrl("http://www.youtube.com/");
mWebView.setWebViewClient(new WebViewClient());
I would suggest using some code to detect the environment of the user... use the iframe code only for ios devices (iphone, ipod, ipad) and use the old code for everyone else.
This Code made exactly fit to different device
webView.setInitialScale(1);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Log.e(SimpleBillsConstants.SIMPLE_BILLS, width + "-" + height);
String data_html = "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"target-densitydpi=high-dpi\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" media=\"screen and (-webkit-device-pixel-ratio:1.5)\" href=\"hdpi.css\" /></head> <body style=\"background:black;margin:0 0 0 0; padding:0 0 0 0;\"> <iframe style=\"background:black;\" width=' "+width+"' height='"+height+"' src=\""+ VIDEO_URL+"\" frameborder=\"0\"></iframe> </body> </html> ";
webView.loadDataWithBaseURL("http://vimeo.com", data_html, "text/html", "UTF-8", null);

Problem with using FusionCharts for Android

I wanted to use FusionCharts with android 2.2 (may be on emulator).
I tried using Javascript and the HTML but did not get the expected result.
Any help??
My code is as follows :
WebView web;
/** Called when the activity is first created. */
#Override
public void on Create(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web=(WebView)findViewById(R.id.webView1);
web.loadUrl("file:///android_asset/Fusioncharts/myChart.html");
}
}
Also my html,xml files :
<html>
<head>
<title>My First chart using FusionCharts
</title>
<script type="text/javascript" src="JavaScripts/FusionCharts.js">
</script>
</head>
<body>
<div id="chartContainer">FusionCharts will load here!
</div>
<script type="text/javascript">
<!--
var myChart = new FusionCharts("Pie2D.swf? dataURL=Data.xml","myChartId", "400", "300", "0", "1" );
myChart.setXMLUrl("Data.xml");
myChart.render("chartContainer");
// -->
</script>
</body>
</html>
and Data.xml :
The above code just displays me : FusionCharts will load here!
Thanks
Sneha
EDIT> NEW CONTENT:
You might need to enable JavaScript and plugins for the WebView:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
http://developer.android.com/reference/android/webkit/WebView.html
What does "install Flash plugin" in WebView mean?
How to Enable Flash Plugin in Webview?
Also you might need to set proper path to the SWF and JS files. Please debug or attach code here.
OLD CONTENT:
There seems to be a JavaScript error or FusionCharts not getting loaded to do the rendering as stated by Duniyadnd.
Please check the Android debug (using adb logcat or other processes) if it traces any error.
Moreover, I did an implementation using PhoneGap which you can check-out from:
PhoneGap API to query call-logs
This is a small PhoneGap Android application which has FusionCharts to show call logs from the device. The post though showcases creation of plugin to get the calllog, you might derive the other elements which you require. Hope this might help.

Categories

Resources