Android Kotlin WebView使用DownloadManager下载文件
Android系统内置提供作为服务的下载管理器DownloadManager,可以很方便下载文件。WebView下载文件可通过该系统服务实现,主要包含两种方式:1)手动下载;2)通过DownloadListner触发下载事件。这里指的是第二种方式。这种触发下载事件的条件是webkit内核WebView浏览的网络地址URL指向的是一个非在线打开展示内容文件。.........
·
Kotlint WebView使用DownloadManager下载文件
思路
Android系统内置提供作为服务的下载管理器DownloadManager,可以很方便下载文件。WebView下载文件可通过该系统服务实现,主要包含两种方式:
1)手动下载;
2)通过DownloadListner触发下载事件。
这里指的是第二种方式。这种触发下载事件的条件是webkit内核WebView浏览的网络地址URL指向的是一个非在线打开展示内容文件。
创建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)
更多推荐


所有评论(0)