協(xié)程是什么
- 是一種在程序中處理并發(fā)任務的方案,也是這種方案的一個組件
- 協(xié)程和線程是屬于一個層級的概念
kotlin在jvm中的協(xié)程是什么
- 是對線程的包裝史汗,線程框架
- 底層用的就是java線程
- 異步操作(切線程)
掛起函數(shù)suspend關鍵字
- 標記和提醒作用儡首,提示方法內(nèi)部要調用掛起函數(shù)做切換線程的作用
- 保證耗時任務放在后臺執(zhí)行
- 為了讓函數(shù)必須在攜程里調用账忘,因為協(xié)程里有他所需要的上下文信息绑改,為了能切回原來的線程
協(xié)程的優(yōu)勢
- 在頻繁切換線程的場景,代碼不會嵌套好幾層,不方便查看
- 協(xié)程啟動的時候,是哪個線程衩辟,就會自動切回它所在的線程
協(xié)程依賴
//協(xié)程
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
用協(xié)程實現(xiàn)下載網(wǎng)絡圖片并展示
- 開啟一個攜程
bt_download.setOnClickListener {
GlobalScope.launch(Dispatchers.Main){
val bitmap = ioCode1()
uiCode1(bitmap)
}
}
- ioCode1方法邏輯代碼
private suspend fun ioCode1():Bitmap? {
val bitmap:Bitmap?= withContext(Dispatchers.IO){
Log.d("zyl--","ioCode1 ${Thread.currentThread().name}")
download()
}
return bitmap
}
download()具體下載邏輯實現(xiàn)
private fun download():Bitmap? {
//1.請求url地址獲取服務端資源的大小
val url = URL(path)
val openConnection: HttpURLConnection = url.openConnection() as HttpURLConnection
openConnection.requestMethod = "GET"
openConnection.connectTimeout = 10 * 1000
openConnection.connect()
val code = openConnection.responseCode
if(code == 200) {
//獲取資源的大小
val filelength = openConnection.contentLength
Log.d("zyl--","size = $filelength")
// //2.在本地創(chuàng)建一個與服務端資源同樣大小的一個文件(占位)
val file = File(getFileName(path))
Log.d("zyl--","path = ${file.absolutePath}")
val inputStream = openConnection.inputStream
val fileOutputStream = FileOutputStream(file)
val buffer = ByteArray(1024)
var i = 0
while (inputStream.read(buffer).also { i = it }!=-1){
fileOutputStream.write(buffer, 0, i)
}
// val bitmap = BitmapFactory.decodeStream(inputStream)
return BitmapFactory.decodeFile(file.absolutePath)
}
return null
}
- uiCode1展示
private fun uiCode1(bitmap: Bitmap?) {
Log.d("zyl--","uiCode1 ${Thread.currentThread().name}")
bitmap?.let {
ivImage.setImageBitmap(bitmap)
}
}