思路

Android系统内置提供作为服务的下载管理器DownloadManager,可以很方便下载文件。WebView下载文件可通过该系统服务实现,主要包含两种方式:
1)手动下载;
2)通过DownloadListner触发下载事件。
这里指的是第二种方式。这种触发下载事件的条件是webkit内核WebView浏览的网络地址URL指向的是一个非在线打开展示内容文件。

Created with Raphaël 2.3.0 开始 创建DownloadManager实例 设置WebView的DownloadListener 确认下载该文件? 猜测文件名 创建下载请求并设置 加入下载队列 结束 结束 yes no

创建DownloadManager实例

downloader = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

Webview设置DownloadListener


webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
                downloadItem(url, contentDisposition, mimetype, contentLength)
            })

实现downloadItem

fun downloadItem(url: String?, contentDisposition: String?, mimeType: String?){
	// ...
}

URLUtil猜测远程文件名

val filename: String = URLUtil.guessFileName(url, contentDisposition, mimeType)

创建并配置下载请求

val uri: Uri = Uri.parse(url)
val request: DownloadManager.Request = DownloadManager.Request(uri)
request.setDestinationInExternalPublicDir(
	"Downloads",
	"mydir/$filename"
)
request.setDescription("Downloading...")
request.setTitle("No.666666")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
request.setMimeType("$mimeType")
// request.setVisibleInDownloadsUi(false)

加入DownloadManager下载队列

val reference = downloader.enqueue(request)
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐