1. 程式人生 > >Android 計時器使用

Android 計時器使用

Android實現定時器3種方式,現將三種方式寫在一個類裡,對比參考:

/**
 * @author huihui 三種計時器
 */
public abstract class MyTimer {
    private int count = 0; // 計時器執行次數
    private int type = 1; // 1表示handle+Thread,2表示handle的postdelay,3表示TimeTask
    private int duration = 0; // 計時器時間間隔
    private boolean flg1 = false; // 計時器1標記
    private
Timer timer; Handler myHandler; public abstract void onTick(); public MyTimer() { count = 0; myHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case
0x123: count++; onTick(); break; default: break; } } }; } public int getCount() { return count; } public void start(int type, int duration) { stop(); count = 0
; this.type = type; this.duration = duration; switch (type) { case 1: // 啟動計時器1 flg1 = true; new Thread(new MyThread()).start(); break; case 2: myHandler.postDelayed(runnable, duration); break; case 3: timer = new Timer(); /** * 第三種計時器方式, timerTask */ TimerTask task = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub myHandler.sendEmptyMessage(0x123); } }; timer.schedule(task, duration, duration); break; default: break; } } public void stop() { // 停止計時器 flg1 = false; switch (type) { case 2: myHandler.removeCallbacks(runnable); break; case 3: timer.cancel(); break; default: break; } } /** * 第二種計時器方式 handle postdelay */ private Runnable runnable = new Runnable() { @Override public void run() { // TODO Auto-generated method stub myHandler.postDelayed(this, duration); count++; onTick(); } }; /** * @author huihui 第一種計時器方式, handle+thread */ class MyThread implements Runnable { @Override public void run() { while (flg1) { try { Thread.sleep(duration); myHandler.sendEmptyMessage(0x123); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }

另還有系統倒計時CountDownTimer類,此類可實現倒計時功能,並在固定間隔收到通知。


    CountDownTimer countDownTimer = new CountDownTimer() {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }
    };

其中OnTick的呼叫是同步的,即前一次呼叫處理完了才有可能處理下一次呼叫。如果處理時間超過OnTick間隔,會漏掉OnTick通知。