Android TimerTask 调用两次时崩溃

发布于 2024-12-10 20:28:03 字数 598 浏览 0 评论 0原文

我在单击按钮时调用我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

送你一个梦 2024-12-17 20:28:03

您是否尝试过为第二次调用创建新的 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?

辞取 2024-12-17 20:28:03

当您重新安排计时器时,它会抛出:

java.lang.IllegalStateException: TimerTask is scheduled already

看来您只能使用计时器一次。

为了重新安排计时器,您每次只需创建它的一个新实例。像下面这样:

// if you have already started a TimerTask, 
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
    m_timer.cancel();

m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);

When you reschedule a Timer, it throws:

java.lang.IllegalStateException: TimerTask is scheduled already

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:

// if you have already started a TimerTask, 
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
    m_timer.cancel();

m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文