当前位置:网站首页>Kotlin collaboration process +flow download case
Kotlin collaboration process +flow download case
2022-06-13 06:26:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
Import dependence
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"// Extension method Read / write file and return , Download progress
inline fun InputStream.copyTo(out: OutputStream, bufferSize: Int = DEFAULT_BUFFER_SIZE, progress: (Long)-> Unit): Long {
var bytesCopied: Long = 0
val buffer = ByteArray(bufferSize)
var bytes = read(buffer)
while (bytes >= 0) {
out.write(buffer, 0, bytes)
bytesCopied += bytes
bytes = read(buffer)
progress(bytesCopied)
}
return bytesCopied
}sealed class DownloadStatus{
data class Progress(val value:Int):DownloadStatus() // Return to download progress
data class Error(val throwable: Throwable):DownloadStatus() // A failure error is returned
data class Done(val file: File):DownloadStatus() // Return results
}This class is an enumeration class , It is the function of encapsulation
object DownloadManager {
fun download(url: String, file: File): Flow<DownloadStatus> {
return flow {
val request = Request.Builder().url(url).get().build()
val response = OkHttpClient.Builder().build().newCall(request).execute() // Use OKHttp To make a network request
if (response.isSuccessful) { // Whether the request is successful
response.body()!!.let { body ->
val contentLength = body.contentLength()// Total length of downloaded content
file.outputStream().use { output ->
val input = body.byteStream()
var emittedProcess = 0L
input.copyTo(output) { bytesCopied ->
val progress = bytesCopied * 100 / contentLength // Calculate download progress
if (progress - emittedProcess > 5) {
delay(100)
emit(DownloadStatus.Progress(progress.toInt()))// Send download progress
emittedProcess=progress
}
}
}
}
emit(DownloadStatus.Done(file)) // Return results
} else {
throw IOException(response.toString()) // No request succeeded in throwing an exception
}
}.catch {
file.delete()// Something goes wrong Delete error file
emit(DownloadStatus.Error(it))// And return error
}.flowOn(Dispatchers.IO)// Switch child threads
}
}Singleton class , Encapsulate download code .
class Fragmentb : Fragment() {
val url:String="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fclubimg.club.vmall.com%2Fdata%2Fattachment%2Fforum%2F202005%2F15%2F230954fsa0bsgqep8zu2j9.jpg&refer=http%3A%2F%2Fclubimg.club.vmall.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637312693&t=4d8c9a64de10cb68fb26d027a0ee4225"
private val mBinding: FragmentFragmentbBinding by lazy {
FragmentFragmentbBinding.inflate(layoutInflater)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return mBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// This process and fragment Life cycle binding
lifecycleScope.launchWhenCreated {
context?.apply {
// External file directory path
val file=File(getExternalFilesDir(null)?.path,"pic.jpg")
DownloadManager.download(url,file).collect {
status->
when(status){
is DownloadStatus.Progress->{ // Download progress
mBinding.apply {
progressBar.progress=status.value
tvProgress.text="${status.value}%"
}
}
is DownloadStatus.Error->{ // Download error
Toast.makeText(context," Download error ",Toast.LENGTH_SHORT).show()
}
is DownloadStatus.Done->{ // Download complete
mBinding.apply {
progressBar.progress=100
tvProgress.text="100&"
}
Toast.makeText(context," Download complete ",Toast.LENGTH_SHORT).show()
}else->{
Log.d("ning"," Download failed ")
}
}
}
}
}
}
}stay fragment Quote and give UI feedback .
Effect demonstration :

边栏推荐
- Wechat applet (function transfer parameters, transfer multiple parameters, page Jump)
- Recent problems
- ‘ipconfig‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- Dart class inherits and implements mixed operators
- Wechat applet custom tabbar (session customer service) vant
- Wechat applet (pull-down refresh data) novice to
- Uniapp dynamically shows / hides the navigation bar return button
- synchronized浅析
- Uni app disable native navigation bar
- 华为开发者认证与DevEco Studio编译器下载
猜你喜欢

AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app

MFS details (vii) - - MFS client and Web Monitoring installation configuration

二分查找

Vector control of Brushless DC motor (4): sensorless control based on sliding mode observer

无刷直流电机矢量控制(四):基于滑模观测器的无传感器控制

Omron Ping replaces the large domestic product jy-v640 semiconductor wafer box reader

After clicking the uniapp e-commerce H5 embedded applet, the page prompts "the page iframe does not support referencing non business domain names"

电镀挂具RFID工序管理解决方案

SSM框架整合--->简单后台管理

The boys x pubgmobile linkage is coming! Check out the latest game posters
随机推荐
RFID process management solution for electroplating fixture
Applet pull-up loading data
Adding classes dynamically in uni app
AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app
Wechat applet uploads pictures (preview deletion limits the size and number of pictures)
Hbuilderx: installation of hbuilderx and its common plug-ins
BlockingQueue source code
App performance test: (IV) power
El form form verification
【Kernel】驱动编译的两种方式:编译成模块、编译进内核(使用杂项设备驱动模板)
Kotlin foundation extension
免费录屏软件Captura下载安装
347. top k high frequency elements heap sort + bucket sort +map
Recent problems
[JS] handwriting call(), apply(), bind()
Commit specification
Huawei developer certification and deveco studio compiler Download
Super model logo online design and production tool
Kotlin basic string operation, numeric type conversion and standard library functions
JVM基础