ACCESSAndroid – 保存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中长按图片点击下载功用了。

相关文章