在Kotlin更新Android的计时器间隔时间
我正在学习kotlin/android,并且我创建了一个timertask
每x秒调用API,具体取决于用户在下拉菜单中的选择。我可以创建任务,但是当用户更新菜单中的间隔(x)值时,创建了一个新任务,并且以前的任务保持运行。
我尝试在计时器上使用取消
,但应用程序崩溃了,说计时器已经取消
。如何更新计时器的间隔值和/或取消以前的实例?
这是Timertask类:
import java.util.*
import java.util.concurrent.TimeUnit
class Schedule {
private val timer = Timer()
fun createTask(task: () -> Unit, intervalSeconds: Long) {
val millisInterval:Long = TimeUnit.SECONDS.toMillis(intervalSeconds)
val startDelay:Long = 0
timer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
task()
}
}, startDelay, millisInterval)
}
fun cancelPrevTask(){
timer.cancel()
}
}
这是活动中的实现:
...
private val schedule = Schedule()
...
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
val item = parent.getItemAtPosition(pos).toString()
showMessage(this, item)
val interval = item.toLong()
// schedule.cancel() <- this crashes the app
schedule.createTask(
{ readFileAndPost(this) },
interval
)
}
I am learning Kotlin/Android and I created a TimerTask
to call an API every x seconds depending on user's choice in a dropdown menu. I can create the task, but when the user updates the interval(x) value in the menu, a new task is created and the previous keeps running.
I tried using cancel
on the timer but the app crashes saying Timer already cancelled
. How can I update the interval value of the timer and/or cancel the previous instances?
This is the TimerTask class:
import java.util.*
import java.util.concurrent.TimeUnit
class Schedule {
private val timer = Timer()
fun createTask(task: () -> Unit, intervalSeconds: Long) {
val millisInterval:Long = TimeUnit.SECONDS.toMillis(intervalSeconds)
val startDelay:Long = 0
timer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
task()
}
}, startDelay, millisInterval)
}
fun cancelPrevTask(){
timer.cancel()
}
}
And this is the implementation in the activity:
...
private val schedule = Schedule()
...
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
val item = parent.getItemAtPosition(pos).toString()
showMessage(this, item)
val interval = item.toLong()
// schedule.cancel() <- this crashes the app
schedule.createTask(
{ readFileAndPost(this) },
interval
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我设法解决了制作
计划
avar
,并在取消任务后创建了类的新实例。这是由此产生的活动:
I managed to solved making
schedule
avar
and creating a new instance of the class after cancelling the task.This is the resulting activity: