Android中java与js相互调用需要通过webview作为中介。
如果需要调用js代码,需要配置webview settings。
webview= (WebView) rootView.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
如果js需要调用java代码,需要增加一个单独的类给js调用,例如:
this.webview.addJavascriptInterface(new JsInteration(),"AppInterface");
public classJsInteration {
@JavascriptInterface
public void getLocalIp() {
System.out.println("getLocalIp");
}
@JavascriptInterface
public void getMacAddress() {
System.out.println("getMacAddress");
}
}
js代码调用
function getMacAddress(){
window.AppInterface.getMacAddress()
}
java调用js代码之前,需要设置
this.webview.setWebChromeClient(new WebChromeClient());
this.webview.setWebViewClient(new WebViewClient());
private class WebViewClient extends WebViewClient {
@Override
public booleanshouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public voidonReceivedError(WebView view,interrorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
}
@Override
public voidonPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
然后可以调用
String jsSend ="javascript:androidKeyHandler.handleUri('nativewebsample://KEY_EVENT;"
+ keycode +";');";
webview.loadUrl(jsSend);
遇到的坑,做了混淆,js总是无法调用java函数。所以需要在proguard文件做如下设置。
-keepclassmembersclass com.philofly.android.activity.WebActivity$JsInteration {
public *;
}
-keepattributes *JavascriptInterface*
网友评论