在js中,有如下代码:
<script>
//js调用安卓
function sendDataToAndroid(){
//调用android程序中的方法,并传递参数。
var name = document.getElementById("name_input").value;
//注意这里的AndroidWebView和方法名chen
window.AndroidWebView.chen(name);
}
//在android代码中调用js代码
function dataFromAndroid(msg){
alert("来自安卓的信息:"+msg);
}
script>
1、在js中调用安卓的话,安卓中写法:
webView.addJavascriptInterface(new JsInterface_2(context), "AndroidWebView");
private class JsInterface_2 {
private Context mContext;
public JsInterface_2(Context context) {
this.mContext = context;
}
//在js中调用window.AndroidWebView.chen(name),便会触发此方法。
@JavascriptInterface
public void chen(String name) {
Log.e("name==" ,name);
}
}
2、安卓调用js中方法,给js传值
注:这个方法要等网页加载完,才有效。所以,要么在网页加载完的监听里调用,要么,写一个点击事件,等加载完了点击调用
传单个值及多个值,见注释
//网页返回键的处理
webView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) { //表示按返回键时的操作
if (webView.canGoBack()) {
webView.goBack(); //后退
} else {
//所在activity销毁
finish();
}
return true; //已处理
}
}
return false;
}
});
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new MyChromeClient());
private class MyChromeClient extends WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
LogU.i("网页title-----" , title);
}
}
// webview设置的代理类
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setJavaScriptEnabled(true);
super.onPageFinished(view, url);
Log.i("详情页加载完成-----" , url);
//调用js中的代码,给网页传用户id
//传多个值的方法。注意单引号的配对
//webView.loadUrl("javascript:dataFromAndroid('" + userInfo.getUserId()+"','"+userInfo.getUserId() + "')");
//传单个值
webView.loadUrl("javascript:dataFromAndroid('" + userInfo.getUserId() + "')");
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("详情页开始加载-----" ,url);
super.onPageStarted(view, url, favicon);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.i("详情页加载异常-----" , failingUrl);
super.onReceivedError(view, errorCode, description, failingUrl);
}
}