日期:2014-05-16 浏览次数:20411 次
// connect to our browser so we can manipulate it
browser = (WebView) findViewById(R.id.calculator);
// set a webview client to override the default functionality
browser.setWebViewClient(new wvClient());
// get settings so we can config our WebView instance
WebSettings settings = browser.getSettings();
// JavaScript? Of course!
settings.setJavaScriptEnabled(true);
// clear cache
browser.clearCache(true);
// this is necessary for "alert()" to work
browser.setWebChromeClient(new WebChromeClient());
// add our custom functionality to the javascript environment
browser.addJavascriptInterface(new CalculatorHandler(), "calc");
// uncomment this if you want to use the webview as an invisible calculator!
//browser.setVisibility(View.INVISIBLE);
// load a page to get things started
browser.loadUrl("file:///android_asset/index.html");
// allows the control to receive focus
// on some versions of Android the webview doesn't handle input focus properly
// this seems to make things work with Android 2.1, but not 2.2
// browser.requestFocusFromTouch();
// Javascript handler
final class CalculatorHandler
{
private int iterations = 0;
// write to LogCat (Info)
public void Info(String str) {
iterations++;
Log.i("Calc",str);
}
// write to LogCat (Error)
public void Error(String str) {
iterations++;
Log.e("Calc",str);
}
// sample to retrieve a custom - written function with the details provided
// by the Android native application code
public String GetSomeFunction()
{
iterations++;
return "var q = 6;function dynamicFunc(v) { return v + q; }";
}
// Kill the app
public void EndApp() {
iterations++;
finish();
}
public void setAnswer(String a)
{
iterations++;
Log.i(tag,"Answer [" + a + "]");
}
public int getIterations()
{
return iterations;
}
public void SendHistory(String s)
{
Log.i("Calc","SendHistory" + s);
try {
JSONArray ja = new JSONArray(s);
for (int i=0;i<ja.length();i++) {
Log.i("Calc","History entry #" + (i+1) + " is [" + ja.getString(i)+ "]");
}
} catch (Exception ee) {
Log.e("Calc",ee.getMessage());
}
}
}
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=0.25,
user-scalable=yes" />
<title>Android to JavaScript with JSON</title>
</head>
<script language="JavaScript">
var cmdHistory = new