package com.zxdemo.utils;

import android.os.Handler;
import android.os.Looper;

public class NonBlockingCountdown {

    private static final long COUNTDOWN_INTERVAL = 1000; // 倒计时时间间隔，单位毫秒
    private final Handler handler = new Handler(Looper.getMainLooper());
    private Runnable countdownRunnable;

    public NonBlockingCountdown(int s, TimeOut timeOut) {
        this.countdownRunnable = new Runnable() {
            int seconds = s;

            @Override
            public void run() {
                if (seconds > 0) {
                    seconds--;
                    // 在这里更新UI，显示剩余时间
                } else {
                    // 倒计时结束，可以在这里做一些操作，比如通知用户
                    handler.removeCallbacks(this);
                    timeOut.timeOut();
                }
            }
        };
    }


    public void start() {
        handler.postDelayed(countdownRunnable, COUNTDOWN_INTERVAL);
    }

    public void cancel() {
        handler.removeCallbacks(countdownRunnable);
    }
}