zihadrizkyef

RequestBodyWithProgress.kt

Jan 21st, 2018
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.86 KB | None | 0 0
  1. package com.android.gotosehat.registrasi_new
  2.  
  3. import android.os.Handler
  4. import android.os.Looper
  5. import okhttp3.MediaType
  6. import okhttp3.RequestBody
  7. import okio.BufferedSink
  8. import java.io.IOException
  9.  
  10. /**
  11.  * بِسْمِ اللهِ الرَّحْمٰنِ الرَّحِيْمِ
  12.  * Created by zihadrizkyef on 15/09/17.
  13.  */
  14. class RequestBodyWithProgress(private val contentType: MediaType, private val mString: String, private val mListener: UploadCallbacks) : RequestBody() {
  15.  
  16.     override fun contentType(): MediaType? {
  17.         return contentType
  18.     }
  19.  
  20.     @Throws(IOException::class)
  21.     override fun contentLength(): Long {
  22.         return mString.length.toLong()
  23.     }
  24.  
  25.     @Throws(IOException::class)
  26.     override fun writeTo(sink: BufferedSink) {
  27.         val stringLength = mString.length
  28.         val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
  29.         val sis = mString.byteInputStream()
  30.         var uploaded: Long = 0
  31.  
  32.         sis.use {
  33.             val handler = Handler(Looper.getMainLooper())
  34.             var read = it.read(buffer)
  35.             while (read != -1) {
  36.                 handler.post(ProgressUpdater(uploaded, stringLength.toLong()))
  37.  
  38.                 uploaded += read.toLong()
  39.                 sink.write(buffer, 0, read)
  40.                 read = it.read(buffer)
  41.             }
  42.         }
  43.     }
  44.  
  45.     interface UploadCallbacks {
  46.         fun onProgressUpdate(percentage: Int)
  47.     }
  48.  
  49.     private inner class ProgressUpdater(uploaded: Long, total: Long) : Runnable {
  50.         private var mUploaded: Long = 0
  51.         private var mTotal: Long = 1
  52.  
  53.         init {
  54.             mUploaded = uploaded
  55.             mTotal = total
  56.         }
  57.  
  58.         override fun run() {
  59.             mListener.onProgressUpdate((100 * mUploaded / mTotal).toInt())
  60.         }
  61.     }
  62.  
  63.     companion object {
  64.         private const val DEFAULT_BUFFER_SIZE = 2048
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment