美文网首页
Android WebView 弹出选项并保存图片到本地

Android WebView 弹出选项并保存图片到本地

作者: _发强 | 来源:发表于2022-06-02 11:34 被阅读0次

    为 WebView 注册配置

    registerForContextMenu(webView);
    

    添加保存方法

    @Override
    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo){
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
    
        final WebView.HitTestResult webViewHitTestResult = webView.getHitTestResult();
    
        if (webViewHitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE || webViewHitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            contextMenu.add(0, 1, 0, "保存图片到本地")
                    .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem menuItem) {
    
                            String DownloadImageURL = webViewHitTestResult.getExtra();
                            String fileName = URLUtil.guessFileName(DownloadImageURL, null, null);
                            if(URLUtil.isValidUrl(DownloadImageURL)){
                                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadImageURL));
                                request.allowScanningByMediaScanner();
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
                                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                downloadManager.enqueue(request);
    
                                Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
                            }
                            else {
                                Toast.makeText(MainActivity.this,"保存失败",Toast.LENGTH_LONG).show();
                            }
                            return false;
                        }
                    });
        }
    }
    

    相关文章

      网友评论

          本文标题:Android WebView 弹出选项并保存图片到本地

          本文链接:https://www.haomeiwen.com/subject/eekqmrtx.html