gpt4 book ai didi

java - 暂停计时器然后继续

转载 作者:行者123 更新时间:2023-12-01 17:46:46 26 4
gpt4 key购买 nike

请参阅@Yuri 从此处发布的代码。 How to stop a timer after certain number of times 。如果我想因为某种情况停止它然后再次重新启动它。我该如何去做呢?

    private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
if(++counter == 4) {
timer.cancel();
}

//do some stuff in my app
//restart the timer again

}
};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.schedule(task, DELAY, DELAY);

}

这是我尝试过的方法,但它总是让我崩溃。

    final int DELAY = 10000;
Timer timer;
MyTask task;
startManager Scanner;
Handler handler;



public class MyTask extends TimerTask {

@Override
public void run() {
handler.post(new Runnable() {
public void run() {
//do Stuff here
}
});
}
public class startManager {

public startManager() {
handler = new Handler();
timer = new Timer();
}

public void start() {

timer.schedule(task, 0, DELAY);
}

public void cancel() {

timer.cancel();
timer.purge();

}
}

}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Scanner = new startManager();
//do some stuff
if (...)
Scanner.cancel()
//restart the timer and its task
Scanner=new startManager();
}

最佳答案

弄清楚了,是因为我没有在startManager()中初始化任务

关于java - 暂停计时器然后继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60854983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com