Android与cocos2dx中的定时器

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类非常的像呢!





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值