android – 如何在一定次数后停止计时器

前端之家收集整理的这篇文章主要介绍了android – 如何在一定次数后停止计时器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试使用Timer运行4次,每次间隔10秒.

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

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,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);
}
原文链接:https://www.f2er.com/android/317133.html

猜你在找的Android相关文章