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

标签 android timer timertask

尝试使用 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, "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);
}

关于android - 如何在一定次数后停止计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11489988/

相关文章:

ios - 如果某个 NSTimer 是使用 scheduledTimerWithTimeInterval 创建的,我如何找出它在哪个运行循环上?

java - 如何在我的 Android 应用程序中更改(线程的)堆栈大小?

java - 为什么我的一些计时器根本不执行它们的任务?

java - Android Firebase : How is OnCompleteListener working asynchronously if it called on main application thread?

Android:如何在一个 TextView 中组合文本和图标

android - 在 LinearLayout 中放置 3 个按钮以占用相等的空间

android - 显示完整 Android 应用程序的计时器。

android - 每次收到推送通知时,Ionic 2 应用程序都会停止

c# - 高性能定时器与秒表

c# - System.Threading.Timer 保留对它的引用