Android TimerTask 调用两次时崩溃
我在单击按钮时调用我的 TimerTask (m_timer):
m_timer.schedule(m_progressUpdater, 0, 500);
这启动了我的运行方法:
@Override
public void run() {
//do some stuff
progressBar.setProgress(currentProgress);
if (progress >= 100) {
handler.post(new Runnable() {
@Override
public void run() {
CompleteTask();
}
});
}
}
我可以调用一次并且它运行得很好。当我再次调用它时,我的应用程序停止响应。我认为我需要在 CompleteTask() 方法中取消任务,但我尝试取消 TimerTask 和 Timer,但它仍然崩溃。有人知道可能是什么问题吗?
I'm calling my TimerTask (m_timer) upon a button click:
m_timer.schedule(m_progressUpdater, 0, 500);
Which kicks off my run method:
@Override
public void run() {
//do some stuff
progressBar.setProgress(currentProgress);
if (progress >= 100) {
handler.post(new Runnable() {
@Override
public void run() {
CompleteTask();
}
});
}
}
I can call this once and it works perfectly. When I call it again, my app stops responding. I'm thinking that I need to cancel the task in my CompleteTask() method, but I've tried cancelling both the TimerTask and the Timer, and it still crashes. Anyone know what the problem might be?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过为第二次调用创建新的 TimerTask 实例?顺便说一下,不要取消计时器,否则它将取消所有任务。日志说了什么?
Have you tried creating new TimerTask instance for the second call? And by the way, don't cancel the timer otherwise it will cancel all of its task. And what did the log say?
当您重新安排计时器时,它会抛出:
看来您只能使用计时器一次。
为了重新安排计时器,您每次只需创建它的一个新实例。像下面这样:
When you reschedule a Timer, it throws:
It seems that you can only use a timer for once.
In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following: