html5 video play issue in android 4.2 - android

I am creating an app with a WebView thats supposed to play a mp4 video using html5 "video" tag.
This is simple html5 code which is working fine in browser but not in android
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video id="vd1" src="path/video.mp4" type="video/mp4" width="100%" height="100%" loop >
</video>
<script type="text/javascript">
var vid = document.getElementById("vd1");
if(vid){
vid.onloadeddata = function() {
vid.play();
alert("Browser has loaded the current frame");
}
}
/*
var video = document.getElementById('vd1');
if(video){
video.addEventListener('loadeddata', function() {
video.play();
});
}*/
</script>
</body>
</html>
But if i pass in pagefinished like below it is working fine.
webview.setWebViewClient(new WebViewClient() {
// autoplay when finished loading via javascript injection
public void onPageFinished(WebView view, String url) { mMessageContentView.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
so How can i use play event using this script tag in android webview?

Related

How to load pdf from java to object in html

I develop a mobile app hybrid and i want to preview a pdf file that i get from web service.
The problem is the connection to the web service i do from java class and i want to preview the PDF in html.
I search in google and this i have until now and this not work for me.
Here my code:
Main Activity:
public class MainActivity extends AppCompatActivity {
private boolean wantExit;
private ActionsApp doActions;
private WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
doActions = new ActionsApp();
view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadDataWithBaseURL("file:///android_asset/js/index.js", "javascript", "application/javascript", "UTF-8", null);
view.loadUrl("file:///android_asset/html/index.html");
view.addJavascriptInterface(doActions, "action");
setContentView(view);
}
}
ActionsApp Class: this class used for action to the web service
public class ActionsApp {
public ActionsApp(){}
#JavascriptInterface
public String getFile(String idObjStr) {
ObjectVersion objectVer = null;
JSONObject jsonObject = null;
JSONParser jsonParser;
int idObj;
InputStream fileStream;
try {
fileStream = get from web service the file as Stream: application/png
jsonParser = new JSONParser();
jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(fileStream, "UTF-8"))
} catch (ParseException e) {
e.printStackTrace();
}
return jsonObject.toString();
}
}
index.js: when i click on button in another page(not the page that i wrote down here) the start this function in the js file.
function openFile(objectID)
{
$.mobile.changePage( "#pdfFile" );
var container = $('#previewContainer');
var pdfObject = $('#pdfObject').remove();
// The "format=pdf" parameter instructs the server to create a pdf preview
of the file and return it.
pdfObject.attr('type', 'application/pdf')
.attr('data', JSON.parse(window.action.getFile(objectID)));
container.append(pdfObject);
}
index.html: this page is to perview to pdf file that i get from the function in js file through ActionsApp class.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-
1.4.5.min.js"></script>
</head>
<body>
<div id="pdfFile" data-role="page" data-theme="a">
<div data-role="header" data-theme="b">
<h2>pdf</h2>
</div>
<div data-role="content" class="ui-content">
<div id="previewContainer">
<!-- Embed a pdf previewer using an <object> element. This element
is modified in JavaScript. -->
<object id="pdfObject" width="100%" height="100%">
</object>
</div>
</div>
</div>
<link rel="stylesheet" type="text/css"
href="file:///android_asset/css/index.css">
<script src="file:///android_asset/js/index.js"></script>
</body>
</html>
Any suggestions?
Thanks,
Tal

jQuery $.post() is not working in Android WebView

I am trying to call JavaScript from Android but $.post() is not working. I tried it in Postman and it is working.
o/p: output is not defined
MainActivity.java
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/newhtml.html");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl("javascript:loadjs()");
}
});
newhtml.html
<!Doctye HTML>
<html>
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function loadjs(){
console.log("called");
var json_config = {
name: "Donald Duck",
city: "Duckburg"
};
console.log("name "+json_config.name);
console.log("city "+json_config.city)
$.post("http://www.w3schools.com/jquery/demo_test_post.asp",json_config,function(data,status){
console.log("data "+data);
console.log("status "+status);
}).fail(function(response) {
console.log("output is "+response.responseText)
});
}
</script>
</head>
<Body>
<div id="print_host"></div>
</Body>
</html>

Playing Youtube html5 videos on Android Phones using iframe API

I am using the following code to play HTML5 videos
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script type="text/javascript" id="youtubeplayer">
</script>
<script>
document.getElementById('youtubeplayer').style.width=window.innerWidth;
document.getElementById('youtubeplayer').style.height=window.innerHeight;
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
//videoId: localStorage.getItem('videoid'),
videoId : "8UVNT4wvIGY",
width : Math.abs(window.innerWidth*0.99),
height : Math.abs(window.innerHeight*0.99),
allowFullScreen : true,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
Basically I am embedding it in a HTML5 page.
It works very well on Desktop, but on a Android device (Google Nexus 10), it just shows the title of the video and the video doesn't load.
Fitvids plugin worked super well for me and played nicely within the bootstrap framework I was using.
From their github page:
<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.fitvids.js"></script>
<script>
$(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
$("#thing-with-videos").fitVids();
});
</script>
Boom done!

Unable to play audio file (.mp3) in Android through Phonegap

I am trying to develop an android application which can play audio files, through Phonegap framework.
Below is the code for that, which is not the index.html, but another HTML page in the project.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>A New App Try</title>
<!--
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.css" />
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.1/jquery.mobile-1.2.1.min.js"></script>
-->
<script src="/android_asset/www/js/corodova.js"></script>
<link rel="stylesheet" href="/android_asset/www/css/MyownTry.css"/>
<script type="text/javascript" src="cordova.js"></script>
<script src="/android_asset/www/js/jquery-1.10.2.js"></script>
<script src="/android_asset/www/js/jquery.mobile-1.3.2.js"></script>
<link rel="stylesheet" href="/android_asset/www/css/jquery.mobile.structure-1.3.2.css" />
<script type="text/javascript" charset="utf-8">
//Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
/*
function onDeviceReady() {
playAudio("../assets/files/Roja_Flute.mp3");
}
*/
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
if (!playing) {
my_media.play();
document.getElementById('play').src = "/android_asset/www/img/pause_icon.jpg";
playing = true;
} else {
my_media.pause();
document.getElementById('play').src = "/android_asset/www/img/Playicon.png";
playing = false;
}
}
// Pause audio
//
/* function pauseAudio() {
if (my_media) {
my_media.pause();
}
}*/
// Stop audio
//
function stopAudio() {
my_media.stop();
playing = false;
document.getElementById('play').src = "/android_asset/www/img/Playicon.png";}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
<style>
img{
width=30%;
}
</style> </head>
<body>
<br/><br/>
<img id="play" src="/android_asset/www/img/Playicon.png"/>
<!-- <img id="pause"src="/android_asset/www/img/pause_icon.jpg" width="20%"/> -->
<img id="stop" src="/android_asset/www/img/stop_icon.jpg" />
<!-- <p id="audio_position"></p>-->
<br/><br/>
Go back to Home Page
<div data-role="footer">
<p>Copyright 2013 | Mani C | newtolearn.android</p>
</div>
</div>
</body>
</html>
I am expecting icons to be smaller ones, as I have defined in the style element, for 30% of image size. And, I am expecting when I click on the Play icon, the audio file to be played.
Unfortunately both the expected behaviors are not occuring. I am seeing a larger 'Play icon', smaller 'Stop icon' and getting, 'Uncaught Reference Exception: variable playAudio is undefined in index.html'(when in fact, the above HTML code has nothing to do with index.html).
Can somebody, please help and can possibly provide a workaround code..?
Thanks in advance!
Mani

Android 4.0.1 breaks WebView HTML 5 local storage?

I have a simple html5 test page which uses LocalStorage to display / save / redisplay a piece of data.
This code works perfectly in Android 2.3.x but logs an exception in 4.0.1 on line 18 of the html which is the frist localStorage.getItem() call and at this point the JS stops.
Exception: Uncaught Error: SECURITY_ERR: DOM Exception 18 at /data/data/my.app.name/app_htmlData:18
I've also tried setting the database path to getCacheDir() with the same result.
String htmlContent = "HTML content listed below";
File sharedDir = getActivity().getDir("htmlData", Context.MODE_PRIVATE);
WebView browser = (WebView)v.findViewById(R.id.wvBrowser);
browser.setWebChromeClient(new WebChromeClient(){
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(estimatedSize * 2);
}
});
browser.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:doTest()");
});
browser.getSettings().setDatabaseEnabled(true);
browser.getSettings().setDatabasePath(sharedDir.getPath());
browser.getSettings().setDomStorageEnabled(true);
browser.loadDataWithBaseURL(mSharedDir.getPath(),
htmlContent,
"text/html",
"utf-8",
null);
The HTML that the page is rendering is as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Simple localStorage test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function doTest() {
$('#stuff').append('<p>reading</p>');
var item = read();
$('#stuff').append('<p>writing</p>');
localStorage['bar'] = new Date().toUTCString();
$('#stuff').append('<p> </p><p>reading again</p>');
read();
}
function read() {
var item = localStorage.getItem('bar');
if (item == null || (item == undefined)) {
item = '';
}
$('#stuff').append('<p> item: ' + item + '</p>');
return item;
}
</script>
</head>
<body>
<p>-Simple localStorage test-</p>
<div id="stuff"></div>
</body>
</html>
Source available here
Via some discussion with a Google engineer it seems that they've made the decision that the file:// scheme is insecure.
A work around for this is to do the following
browser.loadDataWithBaseURL("http://www.example.com",
htmlContent,
"text/html",
"utf-8",
null);
For android versions less than 4.4, loading data into a webview with a file scheme as a directory:
browser.loadDataWithBaseUrl("file:///android_asset/", html, "text/html", "UTF-8", null);
wont work with localStorage. If I add a filename it does work on older OS versions
browser.loadDataWithBaseUrl("file:///android_asset/test.html", html, "text/html", "UTF-8", null);

Categories

Resources