js android 互调

在main 目录下创建assets 文件夹,然后新建测试文件 sample.html





执行加载上述测试页面
webview.loadUrl("file:///android_asset/sample.html");

// 与js交互
webView.addJavascriptInterface(new JsClient(this), "client");

 public class JsClient {
        private Activity activity;

        public JsClient(Activity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void sweepQRcode() {
            Intent intent = new Intent(activity, ZxingActivity.class);
            startActivityForResult(intent, 1000);
        }

        @JavascriptInterface
        public void copyURL(String url) {
            ClipboardManager cmb = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("registerAddress", url);
            cmb.setPrimaryClip(mClipData);
            ToastUtil.showShortToast("复制成功");
        }

        @JavascriptInterface
        public void saveQRcode(String url) {
            downloadQR(url);
        }

        /**
         * 下载二维码
         *
         * @param url
         */
        private void downloadQR(String url) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Glide.with(activity)
                            .load(url)
                            .asBitmap()
                            .into(new SimpleTarget() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                                    File saveFile = ImageUtil.getSaveFile(resource, String.valueOf(System.currentTimeMillis()));

                                    Uri uri = Uri.fromFile(saveFile);
                                    activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                    ToastUtil.showShortToast("图片已下载到" + saveFile.getAbsolutePath());
                                }
                            });
                }
            });
        }
    }

Android 调用JS 的方法

// 因为该方法在 Android 4.4 版本才可使用,所以使用时需进行版本判断
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                        webView.loadUrl("javascript:sweepResult(\"" + result + "\")");
                    } else {
                        webView.evaluateJavascript("javascript:sweepResult(\"" + result +"\")", new ValueCallback() {
                            @Override
                            public void onReceiveValue(String value) {
                                //此处为 js 返回的结果
                            }
                        });
                    }

你可能感兴趣的:(js android 互调)