gpt4 book ai didi

android - 为什么可以使用在后台线程中创建的处理程序来更新UI?

转载 作者:行者123 更新时间:2023-12-03 13:23:29 26 4
gpt4 key购买 nike

我有一个 worker 类,其中创建了一个处理程序。当我尝试使用在后台线程中创建的处理程序更新我的UI时,它会更新UI,并且这里没有崩溃。理想情况下,它应在后台线程中运行时崩溃。请在下面找到代码:

class WorkerThread(val mainThreadHandler: Handler, handlerThreadName: String) :
HandlerThread(handlerThreadName) {

lateinit var workerThreadHandler: Handler

override fun onLooperPrepared() {
super.onLooperPrepared()
Log.d("LLoyd", "onLooperPrepared")


}


override fun run() {
super.run()
Log.d("LLoyd", "run method called")

}

fun startTask(){
workerThreadHandler = object : Handler(this.looper) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
Log.d(
"Lloyd",
"Message from Main Thread received " + msg.what + " Thread name " +
currentThread().name
)
val message = Message()
message.what = msg.what
mainThreadHandler.sendMessage(message)
}
}

}
}

只需单击以下按钮,即可从 Activity 中调用此startTask():
val workerThread = WorkerThread(mainThreadHandler, "Lloyd")
workerThread.start()
btn_task1.setOnClickListener {
workerThread.startTask()
val message = Message()
message.what = FROM_MAINTHREAD
workerThread.workerThreadHandler.sendMessage(message)
val message1 = Message()
message.what = 55
Log.d("Lloyd ", "Outside Thread name " + Thread.currentThread().name)

workerThread.workerThreadHandler.post {
Log.d("Lloyd ", "Runnable Thread name " + currentThread().name)
btn_task1.text = "Task 2"
tv.text= "YAAAAAAAAAAAAAAAAAAAAAAy"
}
}

任何形式的帮助,我们感激不尽!

最佳答案

When you connect a Handler to your UI thread, the code that handles messages runs on the UI thread.



取自 the docs

我相信,因为您是通过按钮单击(即UI线程)调用 workerThread.startTask()的,所以处理程序也只是将结果返回给UI线程,这就是UI也将更新的原因

关于android - 为什么可以使用在后台线程中创建的处理程序来更新UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62067313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com