如何在一定次数后停止计时器 [英] How to stop a timer after certain number of times

查看:43
本文介绍了如何在一定次数后停止计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 Timer 运行 4 次,每次间隔 10 秒.

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.

我尝试用循环停止它,但它一直崩溃.尝试使用带有三个参数的 schedule(),但我不知道在哪里实现计数器变量.有什么想法吗?

I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule() with three parameters, but I didn't know where to implement a counter variable. Any ideas?

final Handler handler = new Handler(); 
Timer timer2 = new Timer(); 

TimerTask testing = new TimerTask() {
    public void run() { 
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test",
                    Toast.LENGTH_SHORT).show();

            }
        });
    }
}; 

int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
    timer2.schedule(testing, DELAY);
    timer2.cancel();
    timer2.purge();
}

推荐答案

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();
        }
    }
};

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

这篇关于如何在一定次数后停止计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆