Android native和webview中js交互主要是用android注解js方法。主要实现如下:直接上代码
js代码为:
<!doctype html> <html><head> <style type='text/css'> html { font-family:Helvetica; color:#222; } h1 { color:steelblue; font-size:24px; margin-top:24px; } button { margin:0 3px 10px; font-size:12px; } .logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; } </style> </head><body> <h1>WebViewJavascriptBridge Demo</h1> <script> function dealWithRequest(data) { return "hello"; } </script> </body></html>native代码为:
public class WebViewActivity extends AppCompatActivity{ private WebView webView; @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setAppCacheEnabled(false); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webView.getSettings().setBlockNetworkImage(false); webView.getSettings().setBlockNetworkLoads(false); webView.clearCache(true); String url = " file:///android_asset/javas.html"; webView.addJavascriptInterface(new JavaScriptInterface(), "stub"); webView.loadUrl(url); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); JsParse("hello"); } }); } public void JsParse(String data){ String url = "javascript:stub.startFunction(dealWithRequest('" + data + "'));"; webView.loadUrl(url); } private class JavaScriptInterface { @JavascriptInterface public void startFunction(String result) { String aString = result; } } }
native调用js的dealWithRequest方法,并传入参数;js返回数据并且调用startFunction方法。