Android倒计时功能实现

来源:互联网 发布:融资租赁软件系统 编辑:程序博客网 时间:2024/05/16 15:13

- 介绍
在Android开发中倒计时功能还是比较常见的,实现方式网上有人有总结过,大概有Timer、Handler、Thread + Handler等实现方式,下面是我使用Thread + Handler方式实现的倒计时功能,开启新的线程可以减少主线程的阻塞。
- 代码实现

public class CountTimer {    private int mCount;    private int mCountdownInterval;    private static final int WHAT = 0;    private CountThread mThread;    public interface OnCountDownListener {        void onCountDown(int count);    }    private Handler mHandler;    private Context mContext;    public CountTimer(Context mContext, final OnCountDownListener mListener) {        this.mContext = mContext;        mHandler = new Handler(mContext.getMainLooper()) {            @Override            public void handleMessage(Message msg) {                if (msg.what == WHAT) {                    int arg1 = msg.arg1;                    if (mListener != null) {                        mListener.onCountDown(arg1);                    }                }            }        };    }    /**     * 开始倒计时     * @param count 总次数     * @param countDownInterval 每次倒计时的间隔(毫秒为单位)     */    public void start(int count, int countDownInterval) {        this.mCount = count;        this.mCountdownInterval = countDownInterval;        if (mThread != null && mThread.isAlive()) {            // 结束线程,清空MessageQueue            mThread.setReadyStop(true);        } else {            mHandler.removeMessages(WHAT);            mThread = new CountThread();            mThread.start();        }    }    /**     * 取消计时操作     */    public void cancel() {        mHandler = new Handler(mContext.getMainLooper());    }    private class CountThread extends Thread {        private boolean isReadyStop;        public void setReadyStop(boolean isReadyStop) {            this.isReadyStop = isReadyStop;        }        @Override        public void run() {            for (int i = mCount; i >= 1; i--) {                if (isReadyStop) {                    mHandler.removeMessages(WHAT);                    mThread = new CountThread();                    mThread.start();                    return;                }                Message msg = Message.obtain();                msg.what = WHAT;                msg.arg1 = i;                mHandler.sendMessage(msg);                try {                    Thread.sleep(mCountdownInterval);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

代码的思路大致是当需要一次的新的倒计时时。先把上一个线程停止掉,并把MessageQueue中消息清空,然后再新建一个线程开始新的计时操作,这个工具类一般是放置在Activity或者Fragment中使用,一般也会操作资源文件,所以需要在Activity或者Fragment中的onDestroy()方法中调用cancel方法及时更换一个Handler空壳,不然会引起崩溃。代码只提供一种思路,还有很多可以优化的地方。

0 0
原创粉丝点击