Android 中可以通過webview來實現和js的交互,在程序中調用js代碼,只需要將webview控件的支持js的屬性設置為true
Android(Java)與JavaScript(HTML)交互有四種情況:
1) Android(Java)調用HTML中js代碼
2) Android(Java)調用HTML中js代碼(帶參數)
3) HTML中js調用Android(Java)代碼
4) HTML中js調用Android(Java)代碼(帶參數)
下面示例總結這四種情況,直接上干貨:
1) Android(Java)
private void showWebView(){ // webView與js交互代碼
try {
mWebView = new WebView(this);
setContentView(mWebView);
mWebView.requestFocus();
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int progress){
JSAndroidActivity.this.setTitle("Loading...");
JSAndroidActivity.this.setProgress(progress);
if(progress >= 80) {
JSAndroidActivity.this.setTitle("JsAndroid Test");
}
}
});
mWebView.setOnKeyListener(new View.OnKeyListener() { // webview can go back
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return false;
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName("utf-8");
mWebView.addJavascriptInterface(getHtmlObject(), "jsObj");
mWebView.loadUrl("http://192.168.1.121:8080/jsandroid/index.html");
} catch (Exception e) {
e.printStackTrace();
}
}
private Object getHtmlObject(){
Object insertObj = new Object(){
public String HtmlcallJava(){
return "Html call Java";
}
public String HtmlcallJava2(final String param){
return "Html call Java : " + param;
}
public void JavacallHtml(){
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("javascript: showFromHtml()");
Toast.makeText(JSAndroidActivity.this, "clickBtn", Toast.LENGTH_SHORT).show();
}
});
}
public void JavacallHtml2(){
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("javascript: showFromHtml2('IT-homer blog')");
Toast.makeText(JSAndroidActivity.this, "clickBtn2", Toast.LENGTH_SHORT).show();
}
});
}
};
return insertObj;
}