我的应用程序中有一个条件,那就是如何控制计时器。我想要的是恰好在15秒后启动功能,并意味着它应该被取消,并且随着功能结束,它从零开始重新开始。
到目前为止,我所做的是使用timer,并为其设置了1500个延迟和15个重复,但是它一次又一次地启动该功能,我想我在这一行做错了:timer.schedule(doAsynchronousTask, 1500,1 );
这是我完整的计时器代码
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
launchFunction();
}
});
}
};
timer.schedule(doAsynchronousTask, 1500,1 );
void launchFunction(){
Log.d("timer","running");
timer.cancel();
}
但是它没有按预期工作,请帮助我。
最佳答案
阅读文档/**
* Schedule a task for repeated fixed-delay execution after a specific delay.
*
* @param task
* the task to schedule.
* @param delay
* amount of time in milliseconds before first execution.
* @param period
* amount of time in milliseconds between subsequent executions.
* @throws IllegalArgumentException
* if {@code delay < 0} or {@code period <= 0}.
* @throws IllegalStateException
* if the {@code Timer} has been canceled, or if the task has been
* scheduled or canceled.
*/
public void schedule(TimerTask task, long delay, long period) {
if (delay < 0 || period <= 0) {
throw new IllegalArgumentException();
}
scheduleImpl(task, delay, period, false);
}
将时间表设置为timer.schedule(doAsynchronousTask, 15000,15000 );并
维持一个计数器以计数是否达到15次