Pause/Resume TimerTask 不工作的场景

Pause/Resume scenario for TimerTask not working

好的,所以,我想要一个任务运行,并在一段时间后保持运行ning(像JS的setInterval()函数,而TimerTask有一个名为 scheduleAtFixedRate 的方法,它基本上做同样的事情。但是,没有明确的机制来 pauseresumeTimerTask.

我读到,一旦 Timer 被取消,它就完蛋了。

我还了解到可以实现解决方法。

这是我的代码:

Timer t = new Timer();
        t1 = new TimerTask() {
            @Override
            public void run() {

               //Do Something like,
a++;

            }
        };
        t.scheduleAtFixedRate(t1, 0L, 300L); /*Pretty basic till this line. Just a TimerTask ddeclaration and execution via a Timer `t`.*/

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (flag == 1) {

t.scheduleAtFixedRate(t1,0,300);//This call says "TimerTask already scheduled," even though purge removed it.
                } else {
                    t1.cancel(); //cancelling the task so that purge does something.
                    int a = t.purge();//a is 1. Purge worked. TimerTask was removed from the queue.
                    Log.d("The number of tasks",a+"");//1
                    flag = 1;
                }
            }
        });

如何进行这项工作?

但是,如果可以使用 ScheduleExecutorService,是否有人能够实施此评论中提到的内容? Pause/Resume ScheduleExecutorService

在这个例子中,比使用 TimerTimerTask 更好的方法是在 UI 线程上使用 HandlerHandler.postDelayed(...)安排回调。

您没有进行任何繁重的处理或任何其他需要在单独线程上执行回调的操作,并且正在更新需要在 UI 线程上完成的 UI 元素无论如何。