当前位置:网站首页>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 :

边栏推荐
- 超有范的 logo 在线设计制作工具
- The processing and application of C language to documents
- 二分查找
- The title of the WebView page will be displayed in the top navigation bar of the app. How to customize
- You should consider upgrading via
- Solutions to common problems in small program development
- Kotlin foundation extension
- SSM framework integration -- > simple background management
- MFS详解(五)——MFS元数据日志服务器安装与配置
- JS convert text to language for playback
猜你喜欢

MFS详解(六)——MFS Chunk Server服务器安装与配置

Wechat applet (get location)

JVM Foundation

Dart class inherits and implements mixed operators

Detailed explanation of PHP distributed transaction principle

MFS详解(五)——MFS元数据日志服务器安装与配置

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

AI实现亲人“复活”|老照片修复|老照片上色,免费APP推荐

MFS詳解(七)——MFS客戶端與web監控安裝配置

Wechat applet custom tabbar (session customer service) vant
随机推荐
MFS詳解(七)——MFS客戶端與web監控安裝配置
App performance test: (IV) power
Solution: vscode open file will always overwrite the last opened label
MFS explanation (V) -- MFS metadata log server installation and configuration
【案例】一个超级好用的工具 —— 给程序员用的计算器
After clicking the uniapp e-commerce H5 embedded applet, the page prompts "the page iframe does not support referencing non business domain names"
不在以下合法域名列表中,微信小程序解决办法
Custom view
Multiple reception occurs in the uniapp message delivery
Dragon Boat Festival wellbeing, use blessing words to generate word cloud
Echart line chart: different colors are displayed when the names of multiple line charts are the same
【Kernel】驱动编译的两种方式:编译成模块、编译进内核(使用杂项设备驱动模板)
Wechat applet jumps to H5 page with parameters
App performance test: (III) traffic monitoring
Using the shutter floor database framework
【新手上路常见问答】关于技术管理
JS convert text to language for playback
Thread pool learning
pthon 执行 pip 指令报错 You should consider upgrading via ...
本地文件秒搜工具 Everything