2 回答

TA贡献1799条经验 获得超6个赞
消息处理与Android密切相关。但您实际上并不想向处理程序发送消息。您实际上只在该线程上运行代码。因此,与其使用您正在做的消息,不如调用post(Runnable):
val uiThreadHandler = Handler(Looper.getMainLooper())
uiThreadHandler.post {
...
}
为了进一步抽象这一点,您可以使用带有Android扩展的Kotlin Coroutines:Dispatchers.Main
GlobalScrope.launch(Dispatchers.Main) {
...
}
然后,该块将被安排在Android主线程上。如果你没有在块本身中暂停任何东西,这可能是由于你现在没有使用协程,你可能不需要担心取消Job从launch.

TA贡献1829条经验 获得超7个赞
Kotlin 中的简单方法是使用协程和挂起函数
class YourClass : CoroutineScope {
// context for main thread
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + Job()
fun toDoSmth() {
launch {
withContext(Dispatchers.IO) {
// task(1) do smth in another thread
}
// do smth in main thread after task(1) is finished
}
}
}
另请阅读调度程序
添加回答
举报