请参阅@Yuri从这里发贴的代码.
How to stop a timer after certain number of times.如果我想停止它,因为一些条件,然后重新启动它.我该怎么做呢?
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(); } //do some stuff in my app //restart the timer again } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timer.schedule(task,DELAY,DELAY); }@H_404_3@这是我试过的,但它一直在崩溃.
final int DELAY = 10000; Timer timer; MyTask task; startManager Scanner; Handler handler; public class MyTask extends TimerTask { @Override public void run() { handler.post(new Runnable() { public void run() { //do Stuff here } }); } public class startManager { public startManager() { handler = new Handler(); timer = new Timer(); } public void start() { timer.schedule(task,DELAY); } public void cancel() { timer.cancel(); timer.purge(); } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Scanner = new startManager(); //do some stuff if (...) Scanner.cancel() //restart the timer and its task Scanner=new startManager(); }@H_404_3@
解决方法
如果您已经取消了一个计时器,则无法重新启动计时器,您必须创建一个计时器.
看到这个answer,它包含一个视频和源代码我怎么做了类似的事情.
基本上有两种方法:暂停和恢复
暂停:
public void pause() { this.timer.cancel(); }@H_404_3@在简历中:
public void resume() { this.timer = new Timer(); this.timer.schedule( aTask,1000 ); }@H_404_3@这使得暂停/恢复的感觉.
如果您的计时器根据应用程序的状态执行不同的操作,则可以考虑使用StatePattern
拳头定义抽象状态:
abstract class TaskState { public void run(); public TaskState next(); }@H_404_3@并提供尽可能多的州.关键是一个国家引导你到另一个国家.
class InitialState extends TaskState { public void run() { System.out.println( "starting..."); } public TaskState next() { return new FinalState(); } } class FinalState extends TaskState { public void run() { System.out.println("Finishing..."); } public TaskState next(){ return new InitialState(); } }@H_404_3@然后更改计时器中的状态.
Timer timer = new Timer(); TaskState state = new InitialState(); timer.schedule( new TimerTask() { public void run() { this.state.run(); if( shouldChangeState() ) { this.state = this.state.next(); } } },1000 );@H_404_3@最后,如果您需要的是执行相同的事情,但是以不同的速度,您可以考虑使用TimingFramework.它有点复杂,但让我们来做一些很酷的动画,通过允许某些组件的绘画以不同的速度进行(而不是线性的)