kotlin协程

2020-09-23  本文已影响0人  卖炭少年炭治郎

协程是什么

kotlin在jvm中的协程是什么

挂起函数suspend关键字

协程的优势

协程依赖

//协程
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'

用协程实现下载网络图片并展示

  1. 开启一个携程
bt_download.setOnClickListener {
            GlobalScope.launch(Dispatchers.Main){
                val bitmap = ioCode1()
                uiCode1(bitmap)
            }
        }
  1. ioCode1方法逻辑代码
private suspend fun ioCode1():Bitmap? {
        val bitmap:Bitmap?= withContext(Dispatchers.IO){
            Log.d("zyl--","ioCode1 ${Thread.currentThread().name}")
            download()
        }
        return bitmap
    }

download()具体下载逻辑实现

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.在本地创建一个与服务端资源同样大小的一个文件(占位)
            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
    }
  1. uiCode1展示
    private fun uiCode1(bitmap: Bitmap?) {
        Log.d("zyl--","uiCode1 ${Thread.currentThread().name}")
        bitmap?.let {
            ivImage.setImageBitmap(bitmap)
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读