Android – 保存WebView中的图片

前言

项目中有需求在APP的Webview中长按图片可以保存。后来就去研究一下该怎么实现,顺便整理了一下。

WebView基本配置

mWvContent.getSettings().setJavaScriptEnabled(true);
mWvContent.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWvContent.getSettings().setDomStorageEnabled(false);
mWvContent.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
// 自适应屏幕
mWvContent.getSettings().setUseWideViewPort(true);
mWvContent.getSettings().setLoadWithOverviewMode(true);

注册ContextMenu

registerForContextMenu(mWvContent);

重写下面的方法即可保存图片

@Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
        final WebView.HitTestResult webViewHitTestResult = mWvContent.getHitTestResult();
        if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
            webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            contextMenu.setHeaderTitle("网页中下载图片");
            contextMenu.add(0, 1, 0, "点击保存")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
                            String DownloadImageURL = webViewHitTestResult.getExtra();
                            if (URLUtil.isValidUrl(DownloadImageURL)) {
                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                //设置图片的保存路径
                                request.setDestinationInExternalFilesDir(WebViewActivity.this, "/img", "/a.png");                               
                                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);
                                Toast.makeText(WebViewActivity.this, "下载成功", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(WebViewActivity.this, "下载失败", Toast.LENGTH_LONG).show();
                            }
                            return false;
                        }
                    });
        }
    }

需要添加相关权限



这样就可以实现在Webview中长按图片点击下载功能了。

你可能感兴趣的:(Android – 保存WebView中的图片)