Auto playing vimeo videos in Android webview - android

I've managed to get a vimeo video to load and play, using the following. However the autoplay=1 as indicated in the vimeo oembed docs doesn't auto play on load. Anyone found a way to auto play (also need to catch event when video finishes)
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
// how plugin is enabled change in API 8
if (Build.VERSION.SDK_INT < 8) {
mWebView.getSettings().setPluginsEnabled(true);
} else {
mWebView.getSettings().setPluginState(PluginState.ON);
}
mWebView.loadUrl("http://player.vimeo.com/video/24577973?player_id=player&autoplay=1&title=0&byline=0&portrait=0&api=1&maxheight=480&maxwidth=800");

This answer is specific to Vimeo only. After about a dozen failed attempts, here's what I have working. Perhaps it will help somebody else. A thousand apologies to the original authors of other SO answers. I have 'borrowed' a number of patterns below -- just thought it would be handy to have all this in one place, and do not claim them for my own code.
First, I have not found a way around embedding the Vimeo player (i.e. you can't get at the mp4 stream directly -- at least not easily or reliably -- I'm pretty sure that's deliberate). Second, Vimeo offers a javascript library to instrument their player, and using it is fairly unavoidable. Beware, it requires message passing, which is a newer browser feature. This is documented on their API page. Third, as is documented elsewhere on SO, you need to be very careful to wait for parts of the stack to become ready, and to not gun-jump. Fourth, the Vimeo player includes a particularly unhelpful background image meant to convey that the plugin is missing or broken (a little frame of film, common icon for this). What is really means is that your javascript has bombed out someplace, and nothing at all is running. If you see the little bit of film on a blank screen, check your javascript.
Step 1. Set up a WebView. You have this correct above. For reference, here is what I used.
mWebView = new WebView((Context) this);
mWebView.setLayoutParams(new LayoutParams(windowWidth, windowHeight));
mWebView.getSettings().setJavaScriptEnabled(true);
// Watch the sdk level here, < 12 requires 'false
// Wanted to force HTML5/264/mp4, you may want flash
// where still available
mWebView.getSettings().setPluginState(PluginState.OFF);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setUserAgentString("Android Mozilla/5.0 AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
wcc = new MyWebChromeClient();
mWebView.setWebChromeClient(wcc);
wvc = new MyWebViewClient();
mWebView.setWebViewClient(wvc);
Step 2. You need the WebChromeClient if you want video to work on the WebView. That's documented here: http://developer.android.com/reference/android/webkit/WebView.html (See HTML Video Support).
Again, for reference here is what I used.
private class MyWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress == 100) {
// Your page is loaded, but not visible,
// add whatever navigation elements you plan to use here.
// N.B. these are JAVA, not JS nav elements
}
}
#Override
public boolean onConsoleMessage(ConsoleMessage cm) {
// I like to watch in the console. And, since it was
// a very convenient way to monitor the javascript, I
// use it for that too. Purists will object, no doubt
if(cm.message().equalsIgnoreCase("EVENT -- Finish")) {
Log.i(TAG, "---> Finishing . . .");
// Depart the activity
finish();
} else {
Log.d(TAG, " **Console ["+cm.sourceId()+"] ("+cm.lineNumber()+") ["+cm.message()+"]");
}
return(true);
}
#Override
public View getVideoLoadingProgressView() {
// Something entertaining while the bytes arrive
Log.i(TAG, " -------------> Loading Progress . . . ");
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return(inflater.inflate(R.layout.loading_video, null));
}
#Override
public void onShowCustomView(View v, WebChromeClient.CustomViewCallback callback) {
// With great sadness, I report that this never fires.
// Neither does the 'hide'.
}
#Override
public void onHideCustomView() {
}
}
The WebViewClient looks like this:
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String injection = injectPageMonitor();
if(injection != null) {
Log.d(TAG, " ---------------> Page Loaded . . .");
Log.d(TAG, " Injecting . . . ["+injection+"]");
view.loadUrl(injection);
}
}
}
Step 3. You need to build a tiny bit of Javascript to fire the player. I used this:
public String injectPageMonitor() {
return( "javascript:" +
"jQuery(document).ready( function() { " +
"console.log(' === Page Ready ===> Setting up');" +
"console.log(' ==== Sending PLAY Command ===');" +
"var froogaloop = $f('froog');" +
"setTimeout(function() { froogaloop.api('play'); }, 3000);" +
"});");
}
Quick explanation . . . I use jQuery in my JS, that's coming below. That's only for convenience, you can do straight JS if you want to lighten the load. Note that after everything else is ready, the script waits another 3 seconds to actually fire. In my weaker moments, I imagine that the kind folks at Vimeo have a broken "ready" callback. 3 Seconds seems to do it.
Step 4. You need some HTML and JavaScript on the page. I put it in a text file inside the resources (raw/vimeo_frame.html). The file looks like this:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">jQuery.noConflict();</script>
<script src="http://a.vimeocdn.com/js/froogaloop2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready( function() {
var showing_player = false;
var froogaloop = $f('froog');
console.log(' === Page Ready ===> Setting up');
jQuery('.froog_container_class').hide();
jQuery('.console').css('height', '100%');
froogaloop.addEvent('ready', function() {
console.log('==== PLAYER READY ====> Setting Play Callback');
froogaloop.addEvent('play', function(data) {
console.log('EVENT -- Play');
/* No idea why, but if the player isn't displayed, it goes
straight to 'pause'. Probably a feature. So I give it 4x4px
to do it's thing during setup */
jQuery('.froog_container_class').show();
jQuery('.froog_container_class').css('height', '4px');
jQuery('.froog_container_class').css('width', '4px');
jQuery('.froog_container_class').css('overflow', 'hidden');
});
/* I don't want to reveal the video until it is actually
playing. So I do that here */
var showingPlayer = false;
froogaloop.addEvent('playProgress', function(data) {
if(!showingPlayer && data.percent > 0) {
showingPlayer = true;
jQuery('.froog_container_class').show();
jQuery('.froog_container_class').css('height', '_windowHeight');
jQuery('.froog_container_class').css('width', '_windowWidth');
/* Most tablets I tested aren't quick enough to make this work
but one can still hope */
jQuery('#loading').fadeOut('slow');
}
});
});
});
</script>
</head>
<body>
<style>
body {
background-image: url('http://<SomethingEntertainingToWatch>.png');
background-size: contain;
}
.mask {
float: left;
height: _windowHeight;
width: _windowWidth;
z-index: 100;
background: transparent;
display: inline;
position: absolute;
top: 0;
left: 0;
}
.froog_container_class {
position: absolute;
height: _windowHeight;
width: _windowWidth;
left: 0;
top: 0;
display: inline;
z-index: 1;
}
#froog {
display: inline;
height: _windowHeight;
width: _windowWidth;
postion: absolute;
top: 0;
left: 0;
}
</style>
<div id="loading" class="loading"><h1>Loading</h1><img class="loading_anim" src="http://foo.bar.com/assets/global/loading.gif"/>
</div>
<!-- Completely optional, I put a div in front of the player to block controls -->
<div id="mask" class="mask">
</div>
<div id="froog_container" class="froog_container_class">
<iframe id="froog" src="_targetUrl?api=1&title=0&byline=0&portrait=0&player_id=froog" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen>
</iframe>
</div>
</body>
</html>
And I load this html file like so:
public String genMainHTML() {
String code = null;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.vimeo_frame);
byte[] b = new byte[in_s.available()];
in_s.read(b);
code = new String(b);
} catch (Exception e) {
e.printStackTrace();
}
if(code != null) {
code = code.replaceAll("_windowHeight", "" + windowHeight + "px");
code = code.replaceAll("_windowWidth", "" + windowWidth + "px");
code = code.replaceAll("_targetUrl", targetUrl);
return(code);
} else {
return(null);
}
}
And inject it like so:
mDomain = "http://player.vimeo.com";
mWebView.requestFocus(View.FOCUS_DOWN);
targetUrl = extras.getString("URL");
String meat = genMainHTML();
mWebView.loadDataWithBaseURL(mDomain, meat, "text/html", "utf-8", null);
setContentView(mWebView);
Whew! When the WebView is ready, then the html and js go in, including the iframe with the Vimeo player. When the document is loaded, then we wait for the player to become ready. When the player is ready, we add some listeners. And 3 seconds later, we fire the api 'play' method.
Those apple-polishers in the audience may be wondering, for completeness, how does one stop the video? Two bits. First, when it ends, I stop it by watching the console output for a message I display. Thus:
public String injectPageFinisher() {
return( "javascript:" +
"jQuery(document).ready( function() { " +
"console.log(' === Page Ready ===> Tearing down');" +
"console.log(' ==== Sending PAUSE Command ===');" +
"var froogaloop = $f('froog');" +
"froogaloop.api('pause');" +
"jQuery('#froog_container').html('');" +
"});");
}
Which can be inserted like so:
#Override
public void onPause() {
super.onPause();
if(isFinishing()){
// Unload the page
if(mWebView != null) {
Log.i(TAG, " ------> Destroying WebView");
mWebView.destroy();
}
}
finish();
}
The second bit is where the video completes its little self. Thus, in the vimeo_frame.html above, just after the 'play' callback, I put:
froogaloop.addEvent('finish', function(data) {
console.log('EVENT -- Finish');
});
And in the Activity, I put a bit to watch for this -- see above in the onConsoleMessage override.
HOWEVER -- as of this writing, I still have not sorted one nagging problem. The MediaPlayer lives on after the WebView and all its progeny are gone. I'm sure this creates some problems, but I haven't identified them yet.

We've come across the same issue and it seems that Android WebView's (as well as those on iOS) are not programmed to allow auto-start of videos since it's possible that it would eat into someones data plan. You have to actually tap on it unless you want to take Google's WebView as a starting point and roll your own. It's not as easy as it sounds, we tried!

Here is the Simple Solution
Step1- Ensure you have minSdkVersion 17
Step2- mWebView.getSettings().setMediaPlaybackRequiresUserGesture(false); Paste this line on the Vimeo Class.

I had the same issue, I think that you could use this one to make it happen:
public abstract void setMediaPlaybackRequiresUserGesture (boolean
require)
Added in API level 17 Sets whether the WebView requires a user gesture
to play media. The default is true.
Parameters require whether the WebView requires a user gesture to play
media
Hope to help you at least a little!

Hope it might help someone new to this.
Please try the below settings to your webview.
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
webSettings.setMediaPlaybackRequiresUserGesture(false);
And append autoplay=1 with your Vimeo video url
webView.loadUrl(resLink + "?autoplay=1");
Here the resLink will look like "https://player.vimeo.com/video/your_video_id"

Related

Android WebView "No 'Access-Control-Allow-Origin' header is present on the requested resource"

I'm trying to load a test web page (in my server). Page is:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<iframe width="420" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k?autoplay=1"/>
</body>
</html>
But webView is not loading page. Not even onProgressChanged called after %40-50
Also, this problem occurs all sites that loads js script from url. Including youtube, fb etc.
WebConsole: XMLHttpRequest cannot load https://googleads.g.doubleclick.net/pagead/id. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.youtube.com' is therefore not allowed access.
Here my settings
FrameLayout contentFrame = (FrameLayout) findViewById(R.id.ContentFrame);
WebView mWebView = new WebView(this);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
mWebView.loadUrl("http://ozgur.dk/browser.html");
contentFrame.removeAllViews();
contentFrame.addView(mWebView);
Layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/ContentFrame"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
You can solve this by enabling a WebSetting called setAllowUniversalAccessFromFileURLs
This is happening on the Javascript layer.
You can read up about it here : CORS
Are you sure you are not pausing timers in somewhere? Because this happens when you call mWebView.pauseTimers() when page loading.
You're trying to do a cross-domain request, which is impossible since it's on a different domain than your page is on.
There is however a workaround that.
Using CORS - tutorial by Monsur Hossain
An example using CORS (By Monsur Hossain):
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
As a side note, if you want to run JavaScript on Android:
Execute JavaScript in Android without WebView - tutorial by Wesley Lin
An example using Rhino (by Wesley Lin):
Object[] params = new Object[] { "javaScriptParam" };
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
Context rhino = Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
// Note the forth argument is 1, which means the JavaScript source has
// been compressed to only one line using something like YUI
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
// Get the functionName defined in JavaScriptCode
Object obj = scope.get(functionNameInJavaScriptCode, scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = Context.toString(jsResult);
}
} finally {
Context.exit();
}
Starting with Android 9 (API level 28), cleartext support is disabled by default.
Better install security certificate on your server.
still
To circumvent add following line in Manifest
<application
...
android:label="#string/app_name"
android:usesCleartextTraffic="true"
...
viola...

How to set font size and text color in WebView?

I'm developing an Android application in which I have used an HTML file for help contents. I have used a WebView to display the content and every thing is fine.
The problem is that user can change the theme and font size of the application. How can I propagate these properties to the content of WebView? Exactly how can I change the font size and text color in WebView? Is there a simple way to do that or I should create different HTMLfiles or CSSes? How to handle the size units (dp, sp, ...)?
I will appreciate your help with this situation.
loadUrl("javascript:(document.body.style.backgroundColor ='red');");
loadUrl("javascript:(document.body.style.fontSize ='20pt');");loadUrl("javascript:(document.body.style.color ='yellow');");
On your android application, use following code to load a web page with user chosen font size and color:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new InredisChromeClient(this));
myWebView.setWebViewClient(new InredisWebViewClient(this));
myWebView.clearCache(true);
myWebView.clearHistory();
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl("http://demo.com/content.html?font-size=12&fontcolor=blue");
On the content.html page, enable JavaScript and use jQuery and its function as below:
function getCssValue(sCSS)
{
var sPageURL = window.location.search.substring(1);
var sValues = sPageURL.split('&');
for (var i = 0; i < sValues.length; i++)
{
var sPair = sValues[i].split('=');
if (sPair[0] == sCSS)
{
return sPair[1];
}
}
}
$(document).ready(function(){
// Set the Font Size from URL
$('html').css('font-size', getCssValue('font-size'));
});
It is best to do theme activities using CSS and Javascript. However if we want to pass on some settings from Android to the WebView dynamically, it is possible and a solution is to use the JavascriptInterface. Here is one way of doing it:
Firstly, we define a class which will be used as a bridge between the Android app and the WebView for JS interactions.
Here WebInterface is an inner class in the Activity and hence it has direct access to myWebView, which is a WebView instance variable.
public class WebInterface {
private Activity activity;
public WebInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void changeTheme() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// All of the theme settings could go here, the settings passed on by Android
myWebView.loadUrl("javascript:document.body.style.backgroundColor ='red';");
myWebView.loadUrl("javascript:document.body.style.fontSize ='20pt'");
myWebView.loadUrl("javascript:document.body.style.color ='yellow';");
//OR load your data as shown here http://stackoverflow.com/a/7736654/891092
htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\" />" + htmlData;
// lets assume we have /assets/theme.css file
myWebView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
}
});
}
}
Note that it is very important to run your code in UI Thread otherwise it will not work.
Here is how the Activity registers the WebView with the JavascriptInterface:
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(jsInterface, "JSInterface");
In the HTML file, which the user is viewing, a button or widget could be made to change theme by calling code in Android through the bridge:
<input type="button" value="Say hello" onClick="doChangeTest()" />
<script type="text/javascript">
function doChangeTest(){
JSInterface.changeTheme(); // this calls the changeTheme in WebInterface
}
</script>
First you need to define a webView and after that use below method.
lightFont is your font that you should store in asset folder.
color is your text color.
font size : you can change font size.(for example 20px or medium and etc).
at the end you need to use seconde method to show html on webView
First Method:
public static String getStyledFont(String html) {
boolean addBodyStart = !html.toLowerCase().contains("<body>");
boolean addBodyEnd = !html.toLowerCase().contains("</body");
return "<style type=\"text/css\">" +
"#font-face {font-family: CustomFont;" +
"src: url(\"file:///android_asset/lightFont.ttf\")}" +
"body {color: #787878;}"+
"body {font-family: CustomFont;font-size: x-small;}</style>" +
(addBodyStart ? "<body>" : "") + html +(addBodyEnd ? "</body>" : "");
}
Second method:
String htmlText = getStyledFont(yourText);
webView.loadDataWithBaseURL("file:///android_asset/",
htmlText ,
"text/html; charset=UTF-8", null, null);

Application Error on Android Cordova/Phonegap Application

I have a cordova (2.7.0) android app that is crashing with an Application Error when it tries to load an iframe where the source has a protocol relative (network-path reference) src.
For instance, if the iframe is:
<iframe src="//instagram.com/p/beGdCuhQYl/embed/?wmode=opaque&wmode=opaque" width="800" height="928" style="border:0;" frameborder="0"></iframe>
Then the app tries to load the source from
file://instagram.com/p/beGdCuhQYl/embed/?wmode=opaque&wmode=opaque
Since the html page that loads this iframe is loaded from the file system, it makes sense that it is doing this. However, is there a way to stop the app from crashing? The same cordova app on iOS just doesn't load anything, and has a blank iframe. I would be nice if the android app behaved the same way.
It would be even nicer if there was a way to tell the cordova app to load these types of urls from http:// and not file:// but I think that is asking too much.
Ok, so I ended up doing this in two parts. First part, try to fix as many protocol relative urls as possible in javascript, and the second part was to provide some java code to ignore any that I missed.
First part (uses jQuery)
/**
* Takes text, looks for elements with src attributes that are
* protocol relative (//) and converts them to http (http://)
* #param {String} text the text that you want to fix urls in
* #returns {String} the updated text with corrected urls
*/
fixProtocolRelativeUrlsInText: function(text) {
var $html, $elements;
try {
$html = $('<div>' + text + '</div>');
$elements = $html.find('[src^="//"]');
if ($elements.length) {
$elements.each(function() {
var $this = $(this);
$this.attr('src', 'http:' + $this.attr('src'));
});
return $html.html();
} else {
return text;
}
} catch(ex) {
return text;
}
},
Second part:
/**
* Override the default makeWebViewClient and provide a custom handler for protocol
* relative urls.
*/
#Override
public CordovaWebViewClient makeWebViewClient(CordovaWebView webView) {
//
// We already try to fix protocol relative urls in the javascript. But this is a safety net in case anything
// gets through. So, in order to not crash the app, lets handle these types ourself and just swallow them up
// for now. The url won't load but at least it won't crash the app either. By the time the protocol relative
// url gets in here, it has the file: appended to it already. If it was a true file:// path to something on the
// device, then it will have file:///some/path, and if it was a protocol relative url that was converted to a
// file:// then it will have file://some.domain, so we look for urls that don't have the three /'s
//
final Pattern pattern = Pattern.compile("^file://[^/].*$");
CordovaWebViewClient webViewClient;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
webViewClient = new CordovaWebViewClient(this, webView) {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
Log.i(LOG_TAG, "swallowing url '" + url + "'");
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
};
} else {
webViewClient = new IceCreamCordovaWebViewClient(this, webView) {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
Log.i(LOG_TAG, "swallowing url '" + url + "'");
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
};
}
return webViewClient;
}
Cordova doesn't support protocol relative src, it expects you to specify either file, or http.

render the epub book in android?

I am try to show epub book in android pad. I can parse the html and css, in order to show the book's content and format, perhaps the book include pictures, It seems that I have two option:
use Webview.
Write a customer view, so that it can render html/css --- it seems a very complicated task.
Which is the good way? If I have to use WebView, how about the page break logic, since webview parse one html file in one page, I can not find the page break in webview.
I have developed a native epub player for android and ios
Code I shared here is part of my product source code, copying and pasting of it will not work for you. Consider it as reference.
I have used webview in android and uiwebview in ios making custom view and parsing html/css is almost like developing a new rendering engine (i.e browser).Its a tedious and complex.
Briefly I give you the steps I have followed for android
Create a custom webview
load url and write call back clients (WebViewClient,WebChromeClient)
after webview load do pagination using below method
Code:
private class MyWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
final MyWebView myWebView = (MyWebView) view;
String varMySheet = "var mySheet = document.styleSheets[0];";
String addCSSRule = "function addCSSRule(selector, newRule) {"
+ "ruleIndex = mySheet.cssRules.length;"
+ "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);"
+ "}";
String insertRule1 = "addCSSRule('html', 'padding: 0px; height: "
+ (myWebView.getMeasuredHeight()/getContext().getResources().getDisplayMetrics().density )
+ "px; -webkit-column-gap: 0px; -webkit-column-width: "
+ myWebView.getMeasuredWidth() + "px;')";
myWebView.loadUrl("javascript:" + varMySheet);
myWebView.loadUrl("javascript:" + addCSSRule);
myWebView.loadUrl("javascript:" + insertRule1);
}
}
private class MyWebChromeClient extends WebChromeClient
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
// GlobalConstants.ENABLE_WEB_VIEW_TOUCH = false;
if(newProgress == 100)
{
postDelayed(new Runnable()
{
#Override
public void run()
{
calculateNoOfPages();
}
},300);
}
}
}
private void calculateNoOfPages()
{
if(getMeasuredWidth() != 0)
{
int newPageCount = computeHorizontalScrollRange()/getMeasuredWidth();
}
}
Inject jquery.js into webview:
private void addJQueryJS()
{
String path = "file:///android_asset/JSLibraries/jquery.min.js";
String data = "{\"MethodName\":\"onJQueryJSLoaded\",\"MethodArguments\":{}}";
String callBackToNative = " jsInterface.callNativeMethod('jstoobjc:"+data+"');";
String script = "function includeJSFile()"
+"{"
+"function loadScript(url, callback)"
+"{"
+"var script = document.createElement('script');"
+"script.type = 'text/javascript';"
+"script.onload = function () {"
+"callback();"
+"};"
+"script.src = url;"
+"if(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0])"
+"{"
+"(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(script);"
+"}"
+"else { callback(); }"
+"}"
+"loadScript('"+path+"', function ()"
+"{"
+callBackToNative
+"});"
+"} ; includeJSFile();";
loadUrl("javascript: "+script);
}
wrap all words into spans - used for highlighting text and navigating to a page.
there would be 3 webviews - current page ,next page and previous page.You should set offset to webview scroll according to page count of that chapter.
lets say one .html file has content of 3 pages - previous webview is first page,current webview is second page,next webview is third page but all webviews loaded the same url.But their content offset is different.
write you own page swiping logic instead of using viewpager.Just pass the current page to the adapter then adapter will return you the next page and previous page.by some calculations.
Code:
#Override
public PageView getPreviousView(PageView oldPage)
{
MyWebView oldWebView = ((PageView)oldPage).getWebView();
int chapterIndex = oldWebView.getData().getIndexOfChapter();
int pageIndex = oldWebView.getData().getIndexOfPage();
int pageCount = oldWebView.getData().getChapterVO().getPageCount();
pageIndex--;
if(pageIndex < 0)
{
pageIndex = 0;
chapterIndex--;
if(chapterIndex<0)
{
//return the same page
chapterIndex = 0;
return null;
}
else
{
//previous chapter last page
PageView pageView = new PageView(oldPage.getContext(),_mViewPager);
MyWebView webView= pageView.getWebView();
PageVO data = new PageVO();
data.setChapterVO(_chaptersColl.get(chapterIndex));
data.setIndexOfChapter(chapterIndex);
data.setIndexOfPage(-2);
webView.setData(data);
return pageView;
}
}
else if(pageIndex <= pageCount-1)
{
//same chapter previous page
PageView pageView = new PageView(oldPage.getContext(),_mViewPager);
MyWebView webView= pageView.getWebView();
PageVO data = new PageVO();
data.setChapterVO(_chaptersColl.get(chapterIndex));
data.setIndexOfChapter(chapterIndex);
data.setIndexOfPage(pageIndex);
webView.setData(data);
return pageView;
}
return oldPage;
}
#Override
public PageView getNextView(PageView oldPage)
{
MyWebView oldWebView = ((PageView)oldPage).getWebView();
int chapterIndex = oldWebView.getData().getIndexOfChapter();
int pageIndex = oldWebView.getData().getIndexOfPage();
int pageCount = oldWebView.getData().getChapterVO().getPageCount();
pageIndex++;
if(pageIndex>=pageCount)
{
pageIndex=0;
chapterIndex++;
if(chapterIndex>=_chaptersColl.size())
{
//end of the chapters and pages so return the same page
chapterIndex--;
return null;
}
else
{
//next chapter first page
PageView pageView = new PageView(oldPage.getContext(),_mViewPager);
MyWebView webView= pageView.getWebView();
PageVO data = new PageVO();
data.setChapterVO(_chaptersColl.get(chapterIndex));
data.setIndexOfChapter(chapterIndex);
data.setIndexOfPage(pageIndex);
webView.setData(data);
return pageView;
}
}
else
{
//next page in same chapter
PageView pageView = new PageView(oldPage.getContext(),_mViewPager);
MyWebView webView= pageView.getWebView();
PageVO data = new PageVO();
data.setChapterVO(_chaptersColl.get(chapterIndex));
data.setIndexOfChapter(chapterIndex);
data.setIndexOfPage(pageIndex);
//data.setPageCount(pageCount);
webView.setData(data);
return pageView;
}
}
No need to use any third party libs .Just need to spend good amount of time to write every thing your own.
Nice One, But in Question... :-)
I don't think any Page Break logic for android webview is available, As per your concern WebView is the good choice to display .epub file (You can add many functionality like, highlight, search, bookmark etc..). And If you found that one then what about if device size is changed. What I am doing is, I just display WebPage in webview and disable scroll, Then I can find the max height of webview, and device screen size (Height and width), Now I have put two buttons for next and previous pages, which just scroll page according to height of device size..
Something easy.. Try this if you want to... (This is my personal opinion may be I am wrong on this)
There's this javascript library that takes care of the pagination issue
http://monocle.inventivelabs.com.au/
This project uses it in android
https://github.com/sharathpuranik/chaek-android
Grab the sourcecode and take a look.

In Android Browser link does not always execute onClick causing focus instead

I am trying to program a very standard JS behavior for a link using an HREF
onClick handler, and I am facing a strange problem caused by what I believe to be focus/touch mode behavior on Android.
Sometimes when I click on the link, instead of executing the action, it simply becomes selected/focused, with either just a focus rectangle or even also with a filled focus rectangle (selected as opposed to just focused?).
The pseudo-code right now is
go
I have tried doing something like:
go
But I still get the same pesky problem some of the time.
Try enabling Javascript on the webview.
In the activity that holds the webview, try this...
WebView wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
I was having he same problem, but figured out it was because I did not enabled Javascript.
Try getting rid of the href attribute and see if that helps. For example, this works when viewed with the WebView component:
<p><a onClick="whereami()">Update Location</a></p>
I wonder if it's related to the onclick -- am I correct to assume that every now and then clicking any link does not follow it? To me, this seems related to the way you touch the screen (or how this is interpreted), like maybe by clicking next to the link and dragging a bit, rather than clicking on the link?
(If my assumption is correct, then this might be faulty hardware: maybe you can try on another device? Or maybe it only happens on a particular side of the link if the screen is not aligned well, and then there might be some software offset one can change?)
Try inserting this "driver" into your page code, and let us know if it works . . . It seems to be working on my site which had the same problem:
//Mouse & Touch -> Consistent Click / Mouse Commands -> Useful driver
(function() {
var isTouch = false;
var simulated_flag = 'handler_simulated';
var touch_click_array = {};
const clickMoveThreshold = 20; //Pixels
function mouseHandler(event) {
if (isTouch) {
if (!event.hasOwnProperty(simulated_flag)) {
//Unreliable mouse commands - In my opinion
var fixed = new jQuery.Event(event);
fixed.preventDefault();
fixed.stopPropagation();
}
}
else {
//Mouse commands are consistent
//TODO: generate corresponding touches
}
}
function mouseFromTouch(type, touch) {
var event = document.createEvent("MouseEvent");
event.initMouseEvent(type, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY
, false, false, false, false, 0, null);
event[simulated_flag] = true;
touch.target.dispatchEvent(event);
};
function touchHandler(event) {
var touches = event.changedTouches
,first = touches[0]
,type = ""
;
if (!event.hasOwnProperty(simulated_flag)) {
isTouch = true;
//Simulate mouse commands
switch (event.type) {
case "touchstart":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
touch_click_array[touch.identifier] = { x: touch.screenX, y: touch.screenY };
}
mouseFromTouch("mousedown", first);
break;
case "touchmove":
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
var id = touch.identifier;
var data = touch_click_array[id];
if (data !== undefined) {
if (Math.abs(data.x - touch.screenX) + Math.abs(data.y - touch.screenY) > clickMoveThreshold) {
delete touch_click_array[id];
}
}
}
mouseFromTouch("mousemove", first);
break;
case "touchcancel":
//Not sure what should happen here . . .
break;
case "touchend":
mouseFromTouch("mouseup", first);
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
if (touch_click_array.hasOwnProperty(touch.identifier)) {
mouseFromTouch("click", touch);
delete touch_click_array[touch.identifier];
}
}
break;
}
}
}
document.addEventListener("mousedown", mouseHandler, true);
document.addEventListener("mousemove", mouseHandler, true);
document.addEventListener("mouseup", mouseHandler, true);
document.addEventListener("click", mouseHandler, true);
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
})();
Now it isn't a 100% complete script - multi-touch would probably be a little wonky, and if you built an interface depending on touch commands, it doesn't generate those in this version. But, it fixed my link-clicking problem.
Erm - ps - it's using jQuery. If you need a non-jQuery version, you can probably just remove the new jQuery.Event from the mouseHandler() function (in other words, use the original event: var fixed = event;), and I believe most browsers would be ok. I am not exactly a js compatibility expert though.
PPS - Tested with Android 1.6
PPPS - Had to modify script to allow a threshold - actual devices were having some problems with a move event being fired during the press. Probably not ideal; if anyone wants to chime in on a better way for doing that, I'd be interested in hearing...
Recently I came across exactly the same problem. I was using the onclick on a button. Sometimes it did not execute the javascript at all. The thing that worked for me was that enable the javascript before loading a url in the webview
// Enable javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// To bind javascript code to android
mWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
mWebView.loadUrl(url);

Categories

Resources