问题描述
协同启动
GlobalScope.launch(){
get_message_pulling()
}
我需要从get_message_pulling()
编辑布局,但出现错误
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
解决方法
因为使用GlobalScope.launch()
而不指定协程上下文将使用Dispatchers.Default
而不是MainThread在后台线程上运行代码,因此您只能通过MainThread协程的上下文与UI通信
GlobalScope.launch(){
get_message_pulling()
withContext(Dispatchers.Main) {
// then update the UI
}
}
,
解决了
<div class="timer-display-id">
<h1>Timer </h1>
<p id="timer">00:00:00 </p>
<button id="start-timer" onclick="start()">Start </button>
<button id="stop-timer" onclick="stop()">Stop </button>
</div>
,
您可以使用特定于Android的Dispatchers.Main
来执行UI更新。另外,请避免使用GlobalScope
来启动协程,如here所述。而是选择Dispatchers.Default
或Dispatchers.IO
。
// CPU bound - Dispatchers.Default
// IO bound - Dispatchers.IO
val defaultScope = CoroutineScope(Dispatchers.Default)
defaultScope.launch {
get_message_pulling()
withContext(Dispatchers.Main){
// Your UI updates
}
}