Android实现可自动关闭的定时器

之前一篇文章里有用到过一个封装好的定时器工具类,现在又做了一些升级,支持自定义响应多少次以后自动关闭,这里单独共享出来:
package com.example.util;

import java.util.Timer;
import java.util.TimerTask;

import com.example.CnLog;

import android.os.Handler;
import android.os.Message;

/**
 * Generate a timer object with specified 'delay' and 'period', 
 * you can handle events with 'TimerManager.LOAD_PROGRESS' 
 * and 'TimerManager.CLOSE_PROGRESS', then do your progress.
 * If you want to get 'timerId', just get it from 'arg1'
 * 
 * @author jackie
 *
 */
public class Manager {

	private static final String TAG = TimerManager.class.getSimpleName();
	private Handler mHandler;
	/** Timer **/  
    private Timer timer = null;  
    /** TimerTask **/  
    private TimerTask timerTask = null;
    /** Delay Time in milliseconds **/  
    private int mDelay;
    /** Period in milliseconds **/  
    private int mPeriod;
    /** trigger times **/  
    private int mTimes = -1;
    /** Timer in progressing flag **/  
    public static final int LOAD_PROGRESS = 0;  
    /** Timer close flag **/  
    public static final int CLOSE_PROGRESS = 1;  
    /** TimerId **/  
    private int mTimerId = 0;
    
    /**
     * Construct a unlimited timer
     * 
     * @param delay amount of time in milliseconds before first execution
     * @param period amount of time in milliseconds between subsequent executions
     */
    public TimerManager(int delay, int period) {
    	this.mDelay = delay;
    	this.mPeriod = period;
    }
    
    /**
     * Construct a unlimited timer, with specified handler
     * 
     * @param handler your own handler to handle the events from this timer
     * @param delay amount of time in milliseconds before first execution
     * @param period amount of time in milliseconds between subsequent executions
     */
    public TimerManager(Handler handler, int delay, int period) {
    	this(delay, period);
    	this.mHandler = handler;
    }
    
    /**
     * Construct a times-limited timer
     * 
     * @param delay amount of time in milliseconds before first execution
     * @param period amount of time in milliseconds between subsequent executions
     * @param times auto close timer after how many times, minimum is 1
     */
    public TimerManager(int delay, int period, int times){
    	this(delay, period);
    	if (times < 1) {
    		throw new IllegalArgumentException("times can not smaller than 1");
    	}
    	this.mTimes = times;
    }
    
    /**
     * Construct a times-limited timer, with specified handler
     * 
     * @param handler your own handler to handle the events from this timer
     * @param delay amount of time in milliseconds before first execution
     * @param period amount of time in milliseconds between subsequent executions
     * @param times auto close timer after how many times, minimum is 1
     */
    public TimerManager(Handler handler, int delay, int period, int times) {
    	this(handler, delay, period);
    	if (times < 1) {
    		throw new IllegalArgumentException("times can not smaller than 1");
    	}
    	this.mTimes = times;
    }
    
	public void startTimer() {
		CnLog.w(TAG, "==========> Start timer!");
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override  
                public void run() {
                    Message msg = new Message();  
                    msg.what = LOAD_PROGRESS;  
                    msg.arg1 = (int) (++mTimerId);
                    if (mHandler != null) {
                    	mHandler.sendMessage(msg);
                    }
                    // Have times-limit, and already reached
                    if (mTimes != -1 && mTimerId == mTimes) {
                    	closeTimer();
                    }
                }  
            };
            timer = new Timer();  
            timer.schedule(timerTask, mDelay, mPeriod);  
        }  
    }
  
    public void closeTimer() {
    	CnLog.w(TAG, "==========> Close timer!");
        if (timer != null) {  
            timer.cancel();  
            timer = null;  
        }  
        if (timerTask != null) {  
            timerTask = null;  
        }  
        mTimerId = 0;
        if (mHandler != null) {
        	mHandler.sendEmptyMessage(CLOSE_PROGRESS);
        }
    }
    
    public void setHandler(Handler handler) {
    	this.mHandler = handler;
    }
}


用法很简单,定义自己的handler以响应定时任务,在合适的地方打开和关闭定时器即可:
private void insTimer() {
		Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case TimerManager.LOAD_PROGRESS:
					int timerId = msg.arg1;
					CnLog.d(TAG, "Timer in processing. timerId: " + timerId);
					if (getCodeTv != null) {
						getCodeTv.setVisibility(View.GONE);
					}
					if (resendLl != null) {
						resendLl.setVisibility(View.VISIBLE);
						int remain = MAX_TIMES - timerId;
						String resendDisp = "(" + remain + ")";
						remainTv.setText(resendDisp);
					}
					break;
				case TimerManager.CLOSE_PROGRESS:
					CnLog.d(TAG, "Timer closed.");
					if (getCodeTv != null) {
						getCodeTv.setVisibility(View.VISIBLE);
					}
					if (resendLl != null) {
						resendLl.setVisibility(View.GONE);
					}
					break;
				}
				super.handleMessage(msg);
			}
			
		};
		timer = new TimerManager(handler, 0, 1000, MAX_TIMES);
	}
// Start timer
timer.startTimer();
// Stop timer
timer.closeTimer();

猜你喜欢

转载自lovelease.iteye.com/blog/2261509
今日推荐