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

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

问题描述

试图用一个定时器做,每组10秒的时间间隔运行此4倍。我曾尝试与循环停止,但它总是死机。使用日程安排功能有三个参数都试过了,但我不知道哪里来实现计数器变量。任何想法?

最后的处理程序处理程序=新的处理程序(); 定时器定时器2 =新的Timer(); TimerTask的测试=新的TimerTask(){     公共无效的run(){         handler.post(新的Runnable(){             公共无效的run(){                 Toast.makeText(MainActivity.this,测试,                     Toast.LENGTH_SHORT).show();             }         });     } }; INT DELAY = 10000; 的for(int i = 0; i = 2;!我++){     timer2.schedule(测试,延迟);     timer2.cancel();     timer2.purge(); }

解决方案

 私人最终静态INT DELAY = 10000;
私人最终处理程序处理程序=新的处理程序();
私人最终定时器定时=新的Timer();
私人最终TimerTask的任务=新的TimerTask(){
    私人INT计数器= 0;
    公共无效的run(){
        handler.post(新的Runnable(){
            公共无效的run(){
                Toast.makeText(MainActivity.this,测试,Toast.LENGTH_SHORT).show();
            }
        });
        如果(++计数器== 4){
            timer.cancel();
        }
    }
};

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    timer.schedule(任务,延迟,延迟);
}
 

Trying to use a timer to do run this 4 times with intervals of 10 seconds each. I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule function 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天全站免登陆