管灌系统巡查员智能手机App
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cc.shinichi.library.glide.progress
 
import android.os.Handler
import android.os.Looper
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException
 
/**
 * @author 工藤
 * @email qinglingou@gmail.com
 */
class ProgressResponseBody internal constructor(
    private val url: String,
    private val internalProgressListener: InternalProgressListener?,
    private val responseBody: ResponseBody
) : ResponseBody() {
 
    private lateinit var bufferedSource: BufferedSource
 
    override fun contentType(): MediaType? {
        return responseBody.contentType()
    }
 
    override fun contentLength(): Long {
        return responseBody.contentLength()
    }
 
    override fun source(): BufferedSource {
        bufferedSource = Okio.buffer(source(responseBody.source()))
        return bufferedSource
    }
 
    private fun source(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead: Long = 0
            var lastTotalBytesRead: Long = 0
 
            @Throws(IOException::class)
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                totalBytesRead += if (bytesRead == -1L) 0 else bytesRead
                if (lastTotalBytesRead != totalBytesRead) {
                    lastTotalBytesRead = totalBytesRead
                    mainThreadHandler.post {
                        internalProgressListener?.onProgress(url, totalBytesRead, contentLength())
                    }
                }
                return bytesRead
            }
        }
    }
 
    internal interface InternalProgressListener {
        fun onProgress(url: String?, bytesRead: Long, totalBytes: Long)
    }
 
    companion object {
        private val mainThreadHandler = Handler(Looper.getMainLooper())
    }
}