kotlin 非同步執行緒簡單事例,加http請求,非同步執行緒之間的通訊

CHAT小強發表於2017-05-27

--------------------------------------------------------------------------------------------------------------------------------------------------------

首先編輯非同步執行緒方法

/**
 * @param url 請求網址
 * **/
public fun thread(url : String) : Thread{
    val thread = object : Thread(){
        override fun run() {
            super.run()
            var request = URL(url).readText()
            Log.d("---->request",request)

        }
    }
    thread.start()
    return thread
}
-------------------------------------------------------

在UI執行緒直接呼叫

thread(url)
------------------------------------------------------

也可以volley 等架包

-----------------------------------------------------------------------------------------------------

與ui執行緒進行資料傳輸handler

var handler = object : Handler() {
    override fun handleMessage(msg: Message) {
        super.handleMessage(msg)
        when(msg.what){
         MESSAGE->main_text!!.text = msg.obj.toString()
        }
    }
}
執行緒寫法
public fun thread(url : String) : Thread{
    val thread = object : Thread(){
        override fun run() {
            super.run()
            var request = URL(url).readText()
            var msg = Message()
            msg.what = MESSAGE
            msg.obj = request
            handler.sendMessage(msg)
        }
    }
    thread.start()
    return thread
}
--------------------------------------------------------------


相關文章