在看懂这篇文章之前首先要有javascript基础。
(1) js调用android的方法:
WebView wView;
wView. addJavascriptInterface (Object obj, String interfaceName);
是实例化一个对象,在html的js中调用,第二个参数是实例化对象的别名,如果要使用这个obj,则在js中使用的名字
就是interfaceName。
public class jsWebDemo extends Activity { WebView wView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wView = (WebView)findViewById(R.id.wv1); WebSettings wSet = wView.getSettings(); wSet.setJavaScriptEnabled(true); ProxyBridge pBridge = new ProxyBridge(); wView.addJavascriptInterface(pBridge, "AliansBridge"); wView.loadUrl("file:///android_asset/index.html"); } private class ProxyBridge { public int one () { return 1; } } }
来看一下index.html的内容:
<html> <mce:script language="javascript"><!-- /* This function is invoked by the activity */ function wave() { alert("1"); document.getElementById("droid").src="android_waving.png"; alert("2"); } // --></mce:script> <body> <div id="output">Test page.</div> <a onClick="window.demo.clickOnAndroid()"> <div style="width:100px; margin:0px auto; padding:10px; text-align:center; border:2px solid #202020;" > <img id="droid" src="android_normal.png" mce_src="android_normal.png"/><br> Click me! </div> </a> <input type="submit" value="change to 1" onclick="document.getElementById('output').innerHTML =AliansBridge.one()" /> </body> </html>
这里的AliansBridge即是调用的JAVA对象。
要注意的是,如果你只有一个方法需要被js调用只new一个对象就行:
ProxyBridge pBridge = new ProxyBridge();
wView.addJavascriptInterface(pBridge, "AliansBridge");
如果你需要调用好多个方法,就要把整个android程序所在的类本身实例化传递进去:
wView.addJavascriptInterface(this, "AliansBridge");
(2) android调用js的方法:wView.setWebChromeClient (WebChromeClient client)
要用到Handler更新UI,Handler mHandler = new Handler();
mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new Object(){ /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } }, "demo");
同理,在html中必须有一个名为demo的对象调用clickOnAndroid()方法。
/** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { result.confirm(); return super.onJsAlert(view, url, message, result); } }