本地js与原生交互

1.建立assets目录
在这里插入图片描述
2.loadata.xml内容


<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title></title>
</head>

<body>

<script type="text/javascript" charset="utf-8">
        /**

         * 增加的方法,java调用,同时返回结果到java中

         */
   function jclqBonusRange(t){
       window.stub.Log(t);
      var userid =   Authentication.CTCGetConfig('UserID');
      window.stub.jsCallbackMethod(userid);
   }
</script>
</body>

</html>

3.js回调方法

  /**

     * js方法回调

     */

private class JsToJava {

    @JavascriptInterface

    public void jsCallbackMethod(String result) {
        Log.i(TAG, "result==" + result);

    }

    @JavascriptInterface

    public void Log(String log) {
        Log.i(TAG, "result==" + log);

    }
}

4.原生与js交互方法

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what){
            case LOAD_CONFIG:
                mWebView = new WebView(this.context);
                mWebView.getSettings().setDefaultTextEncodingName("utf-8");

                mWebView.getSettings().setJavaScriptEnabled(true);

                mWebView.addJavascriptInterface(new JsToJava(), "stub");  //JsToJava是内部类,代码在后面。stub是接口名字。

                mWebView.loadUrl("file:///android_asset/loaddata.html"); //js文件路径

                mWebView.setWebViewClient(new WebViewClient() {

                    @Override

                    public void onPageFinished(WebView view, String url) {
                        Log.i(TAG, "url==" + url);
                        handler.sendEmptyMessage(EXE_LOAD);
//                String urlinit = "javascript:footballHelper.Es.jclq.setContent()";

//                mWebView.loadUrl(urlinit);

                    }

                });

                break;
            case EXE_LOAD:


                String url2 = "javascript:jclqBonusRange(" +""  + "," + "" + ")"; //调用js方法
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                   mWebView.loadUrl( "javascript:jclqBonusRange(\" "     +"UserID"+     "\")" );
                } else {
                    mWebView.evaluateJavascript("javascript:jclqBonusRange(\" " + "UserID" + "\")", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {

                        }
                    });
                }

                break;
        }
        return false;
    }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页