如何使用 OkHTTP 测量下载速度?

How measure download speed with OkHTTP?

我正在使用OkHttp3下载文件,我想看看下载速度。但是我不知道如何测量速度。

我尝试在读取缓冲区之前获取当前毫秒数并在写入缓冲区后进行计算,但它总是 returns 静态值。

以下是我的下载功能

fun download(fileName: String) {
    val request = Request.Builder().url(url)
        .get().build()
    val call = OkHttpClient().newCall(request)
    val response = call.execute()

    if (response.isSuccessful) {
        var inputStream: InputStream? = null

        try {
            inputStream = response.body()?.byteStream()
            val buffer = ByteArray(8192)
            val mediaFile = File(downloadDir, fileName)
            val output = RandomAccessFile(mediaFile, "rw")
            output.seek(0)

            while (true) {
                val readed = inputStream?.read(buffer)

                if (readed == -1 || readed == null) {
                    break
                }

                output.write(buffer, 0, readed)
                downloaded.append(readed.toLong())
            }
            output.close()
        } catch (e: IOException) {
            // TODO: handle IOException
            console.log("${e.message}")
        } finally {
            inputStream?.close()
        }
    }
}

很简单的一道题,想多了就糊涂了。无论如何,这是解决方案。

我需要做的就是在 1s 从新下载的字节中减去下载的字节后,将下载的字节存储在一个变量中,这将给我 1s 中的下载字节,然后我可以使用那些字节转换成速度像 kbpsMbps.

fun getSpeed(callback: (String) -> Unit) {
    doAsync {
        var prevDownloaded = 0L
        while (true) {
            if (contentLength != null) {
                if (downloaded.get() >= contentLength!!) {
                    break
                }
            }

            if (prevDownloaded != 0L) {
                callback(formatBytes(downloaded.get() - prevDownloaded))
            }
            prevDownloaded = downloaded.get()
            Thread.sleep(1000)
        }
    }
}