jim*_*myC 16 java android timer
请参阅@Yuri从此处发布的代码.如何在一定次数后停止计时器 .如果我想因某些条件而停止它,然后再重新启动它.我该怎么做呢?
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);
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的,但它一直在让我崩溃.
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, 0, 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();
}
Run Code Online (Sandbox Code Playgroud)
SAL*_*MAN 30
如果您已经取消了一个计时器,则无法重新启动它,您必须创建一个新计时器.
看到这个答案,它包含一个视频和源代码,我是如何做类似的事情.
基本上有两种方法:暂停和恢复
暂停时:
public void pause() {
this.timer.cancel();
}
Run Code Online (Sandbox Code Playgroud)
简历中:
public void resume() {
this.timer = new Timer();
this.timer.schedule( aTask, 0, 1000 );
}
Run Code Online (Sandbox Code Playgroud)
这使得暂停/恢复的感觉.
如果您的计时器根据应用程序的状态执行不同的操作,您可以考虑使用StatePattern
拳头定义一个抽象状态:
abstract class TaskState {
public void run();
public TaskState next();
}
Run Code Online (Sandbox Code Playgroud)
并提供您喜欢的多个州.关键是一个州引导你到另一个州.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你改变计时器中的状态.
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();
}
}
}, 0, 1000 );
Run Code Online (Sandbox Code Playgroud)
最后,如果您需要执行相同的操作,但速度不同,则可以考虑使用TimingFramework.它有点复杂,但让你做一些很酷的动画,允许某些组件的绘画以不同的速率进行(而不是线性)
| 归档时间: |
|
| 查看次数: |
55614 次 |
| 最近记录: |