Android与cocos2dx中的定时器
在做应用中我们经常会用到定时器的东西,比如注册时为了防止用户的频繁点击的倒计时操作......
一.Android中的倒计时操作
1.使用Timer类
Timer timer =new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Log.i("lz","TimerTask do");
}
},1000);
timer出入参数timertask,时间,调用此方法,会在间隔1000毫秒后执行timertask的操作,这个相当于延时操作thread + handler也可以做。
下面是重复操作:
先定义全局的变量
int timerLen = 60000;
Timer timer =new Timer();
然后:
timer.schedule(new TimerTask() {
@Override
public void run() {
// button.setText("time" + timerLen/1000);
timerLen = timerLen -1000;
Log.i("lz","当前时间="+timerLen);
if(timerLen == 0){
timer.cancel();
}
}
},1000,1000);
这里的schedule(timertask,delay,period),第一个参数就是执行的task,第二个参数是执行时的延时时间,第三个时间是间隔执行时间,我这里
是间隔1000毫秒执行一次,可以使用timer的cancel关闭这个循环操作
二.使用系统的CountDownTimer类
class TimeCount extends CountDownTimer {
// 参数依次为总时长,和计时的时间间隔
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
// 计时完毕时触发
@Override
public void onFinish() {
button.setText("重新验证");
}
// 计时过程显示
@Override
public void onTick(long millisUntilFinished) {
button.setClickable(false);
button.setText(millisUntilFinished / 1000 + "秒");
}
}
我们可以继承这个类重写它的方法,在方法回调我们需要做的操作
接下来调用开始执行的操作
TimeCount c= new TimeCount(60000,1000);
c.start();
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
下面是cocos2dx的定时器学习,Android学习着忽略
cocos2dx中的定时操作非常好用,且经常用到,比如延时执行某个操作......
local timerId=nil
local function callback(dt)
print("callback 距离上次所经过的时间=" .. dt)
CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(timerId)
end
timerId= CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(callback, 3, false)
使用scheduleScriptFunc注册函数执行
callback: 回调函数,Scheduler会传递给回调函数一个参数dt,表示距离上次回调所经过的时间
delay:每次调用回调函数的时间间隔
pause: 是否停住,一般设为false就行,否则定时器停住不执行
unscheduleScriptFunc:通过事件的taskid取消这个定时器
我们也可以像timer一样定义执行的次数或者时间,这里就不讲了,和timer的操作一毛一样。是不是和安卓中的timer类非常的像呢!