美文网首页
Kotlin 上手记 —— 协程1

Kotlin 上手记 —— 协程1

作者: 夜远曦白 | 来源:发表于2020-04-17 14:11 被阅读0次

    Kotlin 的协程用力瞥一眼 - 学不会协程?很可能因为你看过的教程都是错的

    https://kaixue.io/kotlin-coroutines-1/

    练习题

    1. 开启一个协程,并在协程中打印出当前线程名。

    我的代码

    打印结果:

    结果

    2. 通过协程下载一张网络图片并显示出来。

    主要代码:(xml 中只放了一个控件 ImageView)

    class MainActivity : AppCompatActivity() {
    
        var imgMain: ImageView? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_new)
    
            imgMain = findViewById(R.id.img_main)
            CoroutineScope(Dispatchers.Main).launch {
                val bitmap = withContext(Dispatchers.IO) {
                    Log.d("MainActivity", "bitmap 当前线程为:" + Thread.currentThread().toString())
                    getImage("https://cdn.pixabay.com/photo/2020/04/10/23/17/waterfall-5028130_960_720.jpg")
                }
                imgMain!!.setImageBitmap(bitmap)
                Log.d("MainActivity", "当前线程为:" + Thread.currentThread().toString())
            }
        }
    
        fun getImage(imgUrl: String): Bitmap {
            var bmp: Bitmap? = null
            try {
                val myUrl = URL(imgUrl)
                val conn = myUrl.openConnection() as HttpsURLConnection
                conn.requestMethod = "GET"
                conn.connectTimeout = 6000
                val code = conn.responseCode
                var inputStream: InputStream? = null
                if (code == 200) {
                    inputStream = conn.inputStream
                    bmp = BitmapFactory.decodeStream(inputStream)
                }
                inputStream!!.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return bmp!!
        }
    }
    

    记得在 AndroidManifest.xml 中加上权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    

    打印结果:

    打印结果

    运行效果:

    运行效果

    相关文章

      网友评论

          本文标题:Kotlin 上手记 —— 协程1

          本文链接:https://www.haomeiwen.com/subject/uhzgmhtx.html