我試圖從下載檔案的函式回傳一個布林值。但是在進度處理程式中,我無法將“true”陳述句回傳給函式。
我找到了一些文章來附加一個介面來進行通信,但不幸的是我無法讓它用于這個 okhttpd 函式。
還有其他選擇嗎?這是我正在使用的代碼。
private fun downloadFile(url: String,key: String):Boolean {
val formBody: RequestBody = FormBody.Builder()
.add("key", key)
.build()
val downloadClient = OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
.build()
val request: Request = Request.Builder()
.url(url)
.post(formBody)
.addHeader("typeAttach", "download")
.build()
downloadClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("failure Response", e.toString())
call.cancel()
}
override fun onResponse(call: Call, response: Response) {
val tmpDl = File(globalPath, Utility.tmpDir "/test.zip")
val sourceBytes = response.body!!.source()
val sourceSize = response.body!!.contentLength()
val sink: BufferedSink = tmpDl.sink().buffer()
var totalRead: Long = 0
var lastRead: Long
while (sourceBytes
.read(sink.buffer, 8L * 1024)
.also { lastRead = it } != -1L
) {
totalRead = lastRead
sink.emitCompleteSegments()
Log.d("progress”, totalRead "/" sourceSize)
}
//return true when its finished
sink.writeAll(response.body!!.source())
sink.close()
}
})
return false
}
uj5u.com熱心網友回復:
嘗試使用回呼的下一個方法:
private fun downloadFile(
url: String,
key: String,
downloadCompleteCallback: () -> Unit
) {
// your code
}
并在while回圈中通知下載完成:
while (sourceBytes.read(sink.buffer, 8L * 1024).also {
lastRead = it } != -1L)
{
totalRead = lastRead
sink.emitCompleteSegments()
if (totalRead == 100) {
downloadCompleteCallback.invoke()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360671.html
