Android可暂停的倒计时简单实现

package com.klx.rvdemo;

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

import androidx.annotation.NonNull;


/**
 * ***********************************************************************
 * <p>
 * Function desc: 倒计时工具类 秒为单位
 * Create by: xi_ongTi_anMing
 * Date: 2020/11/2
 * use:
 * ICountDown cd = new CountDownTool(10) {
 *
 * @Override public void onTick(long time) {
 * Log.e("tag", "time:" + time);
 * }
 * @Override public void finish() {
 * Log.e("tag", "finish");
 * }
 * // to start
 * cd.start();
 * // to pause
 * cd.pause();
 * // to resume
 * cd.resume();
 * // to stop
 * cd.stop();
 * <p>
 * ************************************************************************
 */

interface ICountDown {
    void start();
    
    void pause();

    void resume();

    void stop();
}

abstract class CountDownTool implements ICountDown {

    private long mTotalTime;// 计时总时长
    private boolean isPause;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Long second = (Long) msg.obj;
            if (second == 0) {
                finish();
                return;
            }
            if (!isPause) {
                onTick(second);
                second--;
            }

            Message message = obtainMessage();
            message.obj = second;
            sendMessageDelayed(message, 1000);
        }
    };

    public CountDownTool(long mTotalTimeSecond) {
        this.mTotalTime = mTotalTimeSecond;
    }

    @Override
    public void start() {
        isPause = false;
        mHandler.removeCallbacksAndMessages(null);
        Message msg = mHandler.obtainMessage();
        msg.obj = mTotalTime;
        mHandler.sendMessage(msg);
    }

    @Override
    public void stop() {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void pause() {
        isPause = true;
    }

    @Override
    public void resume() {
        isPause = false;
    }

    protected abstract void onTick(long second);
    protected abstract void finish();

}

猜你喜欢

转载自blog.csdn.net/qq_17441227/article/details/109452026
今日推荐