android中WebView和javascript实现数据交互实例
本文导语: 在看懂这篇文章之前首先要有javascript基础。 (1) js调用android的方法: 代码如下:WebView wView; wView. addJavascriptInterface (Object obj, String interfaceName); 是实例化一个对象,在html的js中调用,第二个参数是实例化对象的别名,如果要使...
在看懂这篇文章之前首先要有javascript基础。
(1) js调用android的方法:
wView. addJavascriptInterface (Object obj, String interfaceName);
是实例化一个对象,在html的js中调用,第二个参数是实例化对象的别名,如果要使用这个obj,则在js中使用的名字
就是interfaceName。
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的内容:
这里的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.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);
}
}