Android Kotlin - 使用 DownloadManager 下载图片
binding.appBarMain.fab.setOnClickListener { view ->
val url = 'https://ts1.cn.mm.bing.net/th/id/R-C.b0ea268fa1be279d112489ce83ad4696?rik=qItsh%2fBiy33hlg&riu=http%3a%2f%2fwww.quazero.com%2fuploads%2fallimg%2f140303%2f1-140303215009.jpg&ehk=S6PLWamt%2bMzQV8uO9ugcU5d5M19BpXtCpNz2cRJ7q9M%3d&risl=&pid=ImgRaw&r=0'
val request = DownloadManager.Request(Uri.parse(url))
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, '1/1.png')
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
}
这段代码演示了如何使用 DownloadManager 下载图片。
-
创建
DownloadManager.Request对象: 使用Uri.parse(url)将 URL 解析成Uri对象,然后创建DownloadManager.Request对象。 -
设置下载路径: 使用
setDestinationInExternalPublicDir()方法指定下载到外部存储的 Downloads 文件夹下的特定路径。 -
获取
DownloadManager对象: 使用getSystemService()方法获取系统提供的DownloadManager对象。 -
开始下载: 使用
enqueue()方法开始下载任务。
注意:
- 为了使用外部存储,需要在 AndroidManifest.xml 中添加
android.permission.WRITE_EXTERNAL_STORAGE权限。 - 可以根据需要更改下载路径和文件名。
- 可以使用
DownloadManager.Query查询下载状态。
原文地址: https://www.cveoy.top/t/topic/lC4W 著作权归作者所有。请勿转载和采集!