【发布时间】:2021-08-16 14:01:49
【问题描述】:
我想在用户触摸按钮时调用一些代码。当用户停止按下时,应用程序应该停止向服务器发送信息 - 音频块。我想我应该使用协程。但屏幕冻结,应用中断。
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
runBlocking {
var job : Job? = null
when (event?.action) {
MotionEvent.ACTION_DOWN -> {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
while (isActive) { // cancellable computation loop
// print a message twice a second
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
}
}
}
MotionEvent.ACTION_UP -> {
println("main: I'm tired of waiting!")
job?.cancelAndJoin() // cancels the job and waits for its completion
println("main: Now I can quit.")
}
else ->
Log.i("else", "else")
}
}
return v?.onTouchEvent(event) ?: true
}
})
我想,当使用带有 MotionEvent 的 onTouch 时会发生这种情况。怎么了?我该怎么办?
【问题讨论】:
标签: android android-studio kotlin kotlin-coroutines