我有一个URL数组,每个URL提供一个zip文件。我想下载它们并将它们存储在内部存储器中的应用程序文件夹中。
问题:
由于我不知道需要访问的URL数量,因此最好的方法是什么?我刚刚开始使用Kotlin协程。
这是我的“从网址下载”方法
fun downloadResourceArchiveFromUrl(urlString: String, context: Context): Boolean {
Timber.d("-> Started downloading resource archive.. $urlString")
lateinit var file: File
try {
val url = URL(urlString)
val urlConn = url.openConnection()
urlConn.readTimeout = 5000
urlConn.connectTimeout = 10000
val inputStream = urlConn.getInputStream()
val buffInStream = BufferedInputStream(inputStream, 1024 * 5)
val fileNameFromUrl = urlString.substringAfterLast("/")
file = File(context.getDir("resources", Context.MODE_PRIVATE) , fileNameFromUrl)
val outStream = FileOutputStream(file)
val buff = ByteArray(5 * 1024)
while (buffInStream.read(buff) != -1){
outStream.write(buff, 0, buffInStream.read(buff))
}
outStream.flush()
outStream.close()
buffInStream.close()
} catch (e: Exception) {
e.printStackTrace()
Timber.d("Download finished with exception: ${e.message} -<")
return false
}
Timber.d("Download finished -<")
return true
}
您能简单地创建一个循环并每次调用下载方法吗?
for (i in resources.indices) {
asyncAwait {
downloadResourcesFromUrl(resources[i].url, context)
return@asyncAwait
}
此外,同步执行此操作是否是一个好主意?等待每个文件下载,然后继续下一个文件?
答案 0 :(得分:1)
将阻止下载功能转变为暂停状态:
suspend fun downloadResourceArchiveFromUrl(
urlString: String, context: Context
): Boolean = withContext(Dispatchers.IO) {
... your function body
}
现在在launch
的协程中运行循环:
myActivity.launch {
resources.forEach {
val success = downloadResourceArchiveFromUrl(it.url, context)
... react to success/failure ...
}
}
还要确保对您的活动正确实施structured concurrency。