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;
                        }
                    });
        }
    }

需加上相关权限

<uses-permission android:name=”android.permission.INTERNET”/>
<uses-permission
android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses-permission
android:name=”android.permission.ACCESS_NETWORK_STATE” />

如此就是得兑现以Webview中长按图点击下充斥功能了。

相关文章