更新(已测试)
选项 1:使用Glide
private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
withContext(Dispatchers.IO) {
val gifBuffer = Glide.with(context).asGif().load(imageUrl).submit().get().buffer
val imageUri = getImageUri(getApplication(), fileName, folderName)
context.contentResolver.openOutputStream(imageUri).use {
val bytes = ByteArray(gifBuffer.capacity())
(gifBuffer.clear() as ByteBuffer).get(bytes) //Both ".clear()" and "as ByteBuffer" are mandatory!!
it?.write(bytes)
}
}
}
选项 2:使用URL(url).openStream()
private suspend fun downloadImage(context: Context, imageUrl: String, fileName: String, folderName: String) {
withContext(Dispatchers.IO) {
val imageUri = getImageUri(getApplication(), fileName, folderName)
URL(imageUrl).openStream().use { inputStream ->
context.contentResolver.openOutputStream(imageUri).use { outputStream ->
inputStream.copyTo(outputStream!!)
}
}
}
}
我认为你应该使用DownloadManager来实现它,它有setDestinationUri()。
记得先生成图片文件uri:
private fun getNewImageUri(fileName: String, folderName: String): Uri { //create new file
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName) //file name
put(MediaStore.MediaColumns.MIME_TYPE, "image/gif") //file type
put(MediaStore.MediaColumns.RELATIVE_PATH, "${Environment.DIRECTORY_DOWNLOAD}/$folderName") //file location
}
return requireContext().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
}