定时器

Android中常用定时器

Timer

使用Timer可以每隔一段时间执行一次,与TimerTask一起使用。

 Timer timer = new Timer();
 TimerTask taskcc = new TimerTask() {
     public void run() {
         runOnUiThread(new Runnable() {
             public void run() {
                          //每次执行的代码
                        }
                    }
                });           
        };
 // 参数分别是delay(多长时间后执行),duration(执行间隔)
 timer.schedule(taskcc, 1000, 1000);//启动定时器
Handler

使用Handler的postDelayed方法可以实现定时,与Runnable一起使用。

Handler handler = new Handler();
Runnable runnable = new Runnable() {
        @Override
        public void run() {
               //定时执行的代码
        }
//参数分别是runnable(执行的runnable ) ,delay(多长时间后执行)
handler.postDelayed(runnable , 1000);

这样使用定时执行的代码只会执行一次,若要和timer 一样执行多次或一直执行只需在执行代码中再次启动即可。

Handler handler = new Handler();
Runnable runnable = new Runnable() {
        @Override
        public void run() {
               //定时执行的代码
               ... ...
               //定时执行的代码执行之后再次启动即可,此处可以重新设置执行多长时间后执行
               handler.postDelayed(this, 1000);
        }
//参数分别是runnable(执行的runnable ) ,delay(多长时间后执行)
handler.postDelayed(runnable , 1000);
Thread
public class MyThread implements Runnable {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                //执行的代码             
                Thread.sleep(10000);// 线程暂停10秒,单位毫秒
            } catch (InterruptedException e) {          
                e.printStackTrace();
            }
        }
    }
}
// 在需要启动线程的地方加入下面语句:
new Thread(new MyThread()).start();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值