Android WebView 利用ContextMenu 实现长按保存图片到本地

先为 WebView 注册 ContextMenu

registerForContextMenu(mWebView)

添加配置方法

    override fun onCreateContextMenu(
        menu: ContextMenu?,
        v: View?,
        menuInfo: ContextMenu.ContextMenuInfo?
    ) {
        super.onCreateContextMenu(menu, v, menuInfo)
        menu?.let { contextMenu ->
            val webViewHitTestResult: WebView.HitTestResult = mWebView.hitTestResult

            if (webViewHitTestResult.type == WebView.HitTestResult.IMAGE_TYPE || webViewHitTestResult.type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                contextMenu.add(0, 1, 0, "下载图片")
                    .setOnMenuItemClickListener {
                        val DownloadImageURL: String = webViewHitTestResult.extra ?: ""
                        val fileName = URLUtil.guessFileName(DownloadImageURL, null, null)
                        if (URLUtil.isValidUrl(DownloadImageURL)) {
                            val request: DownloadManager.Request =
                                DownloadManager.Request(Uri.parse(DownloadImageURL))
                            request.allowScanningByMediaScanner()
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                            request.setDestinationInExternalPublicDir(
                                Environment.DIRECTORY_DOWNLOADS,
                                fileName
                            )
                            val downloadManager: DownloadManager =
                                getSystemService(DOWNLOAD_SERVICE) as DownloadManager
                            downloadManager.enqueue(request)
                            Toast.makeText(
                                this,
                                "下载成功",
                                Toast.LENGTH_LONG
                            ).show()
                        } else {
                            Toast.makeText(
                                this,
                                "下载失败",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                        false
                    }
            }
        }
    }

你可能感兴趣的:(Android WebView 利用ContextMenu 实现长按保存图片到本地)