简体   繁体   English

在Android中停止并重新启动计时器任务

[英]Stop and restart timer task in Android

I need to stop current running timer Task and restart it with a different delay. 我需要停止当前正在运行的计时器Task并以不同的延迟重新启动它。 I tried several ways but nothing works properly. 我尝试了几种方法,但是都无法正常工作。 When I use the following code, TimerTask is going to run in both delays. 当我使用以下代码时,TimerTask将在两个延迟中运行。

public void restUploadInterval(long newDelay) {
        timerRealData.cancel();
        timerRealData.purge();
        mMqttSupporter = MqttSupporter.getInstance();
        Timer timerRealData = new Timer();
        delay = newDelay;
        UploadingTask uploadingTask = new UploadingTask();
        timerRealData.scheduleAtFixedRate(uploadingTask, delay, delay);
    }

Please let me know how can I stop current timer task and run it again with a different delay. 请让我知道如何停止当前的计时器任务并以不同的延迟再次运行它。

Exactly as you did. 确实和您一样。

To restart a Timer with a different timing, you need to cancel() the old timer and create a new one. 要使用其他计时重启计时器,您需要cancel()旧计时器并创建一个新计时器。

Your code probably is not working just because you are hiding the member variable timerRealData with a local variable with the same name. 您的代码可能无法正常工作,因为您用相同名称的局部变量隐藏了成员变量timerRealData

Try to change: 尝试更改:

Timer timerRealData = new Timer(); 计时器timerRealData = new Timer();

with

timerRealData = new Timer(); timerRealData =新的Timer();

and it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM