WebViewClient 加载完成后调用html

 @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.e("main_web", "onPageFinished");
            StringBuilder sb=new StringBuilder();
            sb.append("javascript:$appLoadPage(");
            sb.append("{\\"terminal\\":\\"android\\",\\"event\\":\\"finished\\"}");
            sb.append(")");
            callJsPageFinished(sb.toString());
        }
### callJsPageFinished
    /***
     * 调用JS  Toast.makeText(MainActivity.this, "JS返回的随机数的值为" + response, Toast.LENGTH_SHORT).show();
     */
    //@RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void callJsPageFinished(String javascript) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript(javascript, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                   //如果有返回值,做出简单响应(JS函数无返回值是,response不为null,而是字符串"null")
                   //if (!response.equals("null")) { }
                }
            });
        }else{
            mWebView.loadUrl(javascript);
        }
    }

首页定义html方法,提供给后端调用

<script type="text/javascript">
    /**
     * app初始化通知方法  必须放前面,否则由于网络问题加载错误
     * @param {os:"android/os"} options 
     */
    // eslint-disable-next-line no-unused-vars
    function $appLoadPage(options) {
      console.log("appPageFinished" + options);
    }
  </script>

JsHook html调用java

/***
     *  被注入对象  提供给html调用
     */
    class JsHook {
        //应用版本信息
        @JavascriptInterface
        public String versionInfo() {
            return APKVersionInfoUtils.versionInfo(MainActivity.this);
        }

        //系统信息
        @JavascriptInterface
        public String systemInfo() {
            return SystemUtil.systemInfo();
        }
    }
 //系统信息
    @JavascriptInterface
    public static String systemInfo() {
        StringBuilder sb=new StringBuilder();
        sb.append("{\\"deviceBrand\\":\\"");
        sb.append(SystemUtil.getDeviceBrand());
        sb.append("\\"");
        sb.append(",\\"language\\":\\"");
        sb.append(SystemUtil.getSystemLanguage());
        sb.append("\\"");
        sb.append(",\\"systemModel\\":\\"");
        sb.append(SystemUtil.getSystemModel());
        sb.append("\\"");
        sb.append(",\\"versionSdk\\":\\"");
        sb.append(Build.VERSION.SDK_INT);
//            sb.append("\\"");
//            sb.append(",\\"imei\\":\\"");
//            sb.append(SystemUtil.getIMEI(MainActivity.this));
        sb.append("\\"}");
        return sb.toString();
    }
public static String versionInfo(Context mContext) {
        StringBuilder sb=new StringBuilder();
        sb.append("{\\"versionCode\\":\\"");
        sb.append(APKVersionInfoUtils.getVersionCode(mContext));
        sb.append("\\"");
        sb.append(",\\"versionName\\":\\"");
        sb.append(APKVersionInfoUtils.getVersionName(mContext));
        sb.append("\\"}");
        return sb.toString();
    }

html调用声明的方法

 loadAppFun(){
     console.log(window.$appHook.versionInfo());
     console.log(window.$appHook.systemInfo());
    },

onCreate

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = findViewById(R.id.web_view);

        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);

        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSavePassword(false);
        //支持js
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setAllowFileAccess(true);// 设置允许访问文件数据
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setAllowContentAccess(true);

        mWebView.setWebViewClient(mWebViewCilent);

        //设置可让界面弹出alert等提示框
        //webView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebChromeClient(new WebChromeClient() {
            //重写onJsAlert方法,做出简单响应
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //只对特殊信息做出响应,避免影响其他警告框
                if (message.equals("测试onJsAlert")) {
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                }
                return super.onJsAlert(view, url, message, result);
            }

            //重写onJsConfirm方法,做出简单响应
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                return super.onJsConfirm(view, url, message, result);
            }

            //重写onJsPrompt方法,做出简单响应
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });
        //设置支持js调用java
        mWebView.addJavascriptInterface(new JsHook(), "$appHook");
        //  String url = "https://bt.sandieji.tech?_fromTerminal=android&vconsole=true";
        String url = "{http://{{ip}}:{{port}}}?_fromTerminal=android&vconsole=true";
        //加载网络资源
        mWebView.loadUrl(url);
    }
文档更新时间: 2021-07-07 08:00   作者:admin