用Kotlin给Android WebView写一个缓存模式,并设置下载路径为/storage/emulated/0/Download
时间: 2023-11-14 19:19:46 浏览: 53
可以使用以下代码来设置缓存模式和下载路径:
```kotlin
val webView = WebView(context)
// 设置缓存模式为LOAD_CACHE_ELSE_NETWORK
webView.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
// 设置下载路径为/storage/emulated/0/Download
val downloadPath = "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}"
webView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
val request = DownloadManager.Request(Uri.parse(url))
request.setTitle("Downloading $url")
request.setDescription("Downloading file...")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationUri(Uri.parse("file://$downloadPath/${URLUtil.guessFileName(url,contentDisposition,mimetype)}"))
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
}
```
注意,需要在AndroidManifest.xml中添加读写存储权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```