【发布时间】:2021-03-01 03:29:36
【问题描述】:
我正在使用 Ktor 库 (io.ktor:ktor-client-android:1.2.5) 下载文件。
当我下载图像时,一切都很好,但是当我想下载 .apk 时,它就不起作用了。
我正在使用ktor 1.2.5。
这是我使用的函数:
suspend fun HttpClient.downloadFile(file: OutputStream, url: String): Flow<DownloadResult> {
return flow {
try {
val response = call {
url(url)
method = HttpMethod.Get
}.response
val data = ByteArray(response.contentLength()!!.toInt())
var offset = 0
do {
val currentRead = response.content.readAvailable(data, offset, data.size)
offset += currentRead
val progress = (offset * 100f / data.size).roundToInt()
emit(DownloadResult.Progress(progress))
} while (currentRead > 0)
response.close()
if (response.status.isSuccess()) {
withContext(Dispatchers.IO) {
file.write(data)
//file.write()
}
emit(DownloadResult.Success)
} else {
emit(DownloadResult.Error("File not downloaded"))
}
} catch (e: TimeoutCancellationException) {
emit(DownloadResult.Error("Connection timed out", e))
} catch (t: Throwable) {
emit(DownloadResult.Error("Failed to connect. ${t.message}"))
}
}
}
我是这样使用它的:
private fun downloadFile(view: View, context: Context, url: String, file: Uri) {
val ktor = HttpClient(Android)
//viewModel.setDownloading(true)
context.contentResolver.openOutputStream(file)?.let { outputStream ->
CoroutineScope(Dispatchers.IO).launch {
ktor.downloadFile(outputStream, url).collect {
withContext(Dispatchers.Main) {
when (it) {
is DownloadResult.Success -> {
//viewModel.setDownloading(false)
view.custom_des_pb_progreso_descarga.progress = 0
Toast.makeText(context, "Descarga Completa", Toast.LENGTH_LONG).show()
dismiss()
viewFile(file, context)
}
is DownloadResult.Error -> {
Toast.makeText(context, "Error al descargar actualización. ${it.message} ${it.cause} ", Toast.LENGTH_LONG).show()
dismiss()
}
is DownloadResult.Progress -> {
view.custom_des_pb_progreso_descarga.progress = it.progress
view.custom_des_pb_conteo_descarga.text = "${it.progress}%"
}
}
}
}
}
}
}
有人知道会发生什么吗?
【问题讨论】:
标签: android kotlin download kotlin-coroutines ktor