我將協程范圍分配給這樣的活動生命周期
class MainActivity : AppCompatActivity(),
CoroutineScope
{
override val coroutineContext: CoroutineContext =
Dispatchers.Main SupervisorJob()
...
override fun onDestroy() {
coroutineContext[Job]!!.cancel()
super.onDestroy()
}
}
現在,如果我在此范圍內啟動 CountDownTimer,則在銷毀活動時它不會被取消。
override fun onCreate(savedInstanceState: Bundle?) {
...
launch {
startTimer()
}
}
fun startTimer(count: Long = 1000) {
object: CountDownTimer(count, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
startTimer()
}
}.start()
}
為什么它不會被取消?以及如何通過取消活動作業來使其被取消?
uj5u.com熱心網友回復:
我不知道你為什么在這里使用協程,但你可以擺脫它,將一個實體保存CountDownTimer到一個變數并在onDestroy方法中取消它:
lateinit var timer: CountDownTimer
override fun onCreate(savedInstanceState: Bundle?) {
...
startTimer()
}
fun startTimer(count: Long = 1000) {
timer = object: CountDownTimer(count, 1000) {
override fun onTick(millisUntilFinished: Long) {}
override fun onFinish() {
startTimer()
}
}.start()
}
override fun onDestroy() {
timer.cancel()
super.onDestroy()
}
為什么它不會被取消?
CountDownTimer有自己的處理刻度的機制,使用Handler. 它不附加到協??程的背景關系中。
協程取消是合作的。協程代碼必須合作才能取消。如果協程在計算中作業并且不檢查取消,那么它不能被取消。
有幾種方法可以使計算代碼可取消:
- 第一個是定期呼叫檢查取消的掛起函式,例如
delay。 - 明確檢查取消狀態,例如
isActive或ensureActive()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463367.html
