安卓kotlin协程中更新UI

        button.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    val sc = Socket(srvUrl, mPort)
                    sc.soTimeout = 10000
                    val os = sc.getOutputStream()
                    val pw = PrintWriter(os)
                    pw.write(textView.text.toString() + "\n")
                    pw.flush()
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@MainActivity, "发送成功.", Toast.LENGTH_LONG).show()
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        Toast.makeText(this@MainActivity, e.toString(), Toast.LENGTH_LONG).show()
                    }
                } finally {
                }
            }
        }

使用按钮button进行耗时操作,socket连接服务器发送数据,发送完成后Toast一条消息,withContext用来切换上下文,简直不要太爽啊。

你可能感兴趣的:(kotlin)