1.html代码
<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script type="text/javascript">
//由java调用此方法
var count = 0;
function wave(){
if(count %2 == 0){
document.getElementById("droid").src="ic_launcher.png";
}else{
document.getElementById("droid").src="app_icon.png";
}
count ++;
}
</script>
</head>
<body>
<a onclick="window.callByJs.clickOnAndroid()">
<img id="droid" src="app_icon.png" mce_src="app_icon.png"/></br>Click me change icon!
</a>
</body>
</html>
2.Android 代码:
package com.example.chenys.webviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* Created by mChenys on 2015/11/19.
* 实现js页面调用android的方法,及android的方法里面再调用js页面的js函数,实现互调的过程.
*/
public class TextCallJsActivity2 extends Activity {
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_call_js);
final WebView webView = (WebView) findViewById(R.id.webView);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Object() {
@JavascriptInterface
public void clickOnAndroid() {
System.out.println("clickOnAndroid被调用了....");
/**
* 注意:这里调用webview的方法必须在同一个线程中完成,否则抛出异常:
* java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread.
* (Expected Looper Looper (main, tid 1) {1d832dfa} called on Looper (JavaBridge, tid 263) {2a93b47f}, FYI main Looper is Looper (main, tid 1) {1d832dfa})
*/
mHandler.post(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:wave()");
}
});
}
}, "callByJs");
webView.loadUrl("file:///android_asset/index2.html");
}
}