Android 与JS进行交互
-
设置支持javascript交互
WebSettings wSet = webView.getSettings(); wSet.setJavaScriptEnabled(true);
- 加载js文件
可以将文件放在资源文件assert文件夹下如:a.html 使用
webView.loadUrl("file:///android_asset/a.html");
加载js文件 或者使用网络文件webView.loadUrl("http://..");
-
设置javascriptinterface接口
webView.addJavascriptInterface(new JavaScriptInterface(), "JSI");
-
JavaScriptInterface内容
public class JavascriptInterface{ @JavascriptInterface public String get() { retutn "js call android by JavascriptInterface."; } }
-
a.html 内容
<script> function showMsgWithoutParams(){ alert("无参函数"); } function showMsg(args){ alert("有参函数"+args); } function callAndroidMethod(){ //js调用android方法 if (window.JSI && window.JSI.get) { alert( window.JSI.get()); } } </script>
-
Android 调用js方式
webview.post(() -> mBinding.webview.loadUrl("javascript:getUserVipInfo()"));
- 调用过程可能会出现 A WebView method was called on thread ‘JavaBridge’. All WebView methods must be called异常,点击链接查看解决方式:主要使用异步调用方式解决即post形式。