package com.zxdemo.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class NonBlockingCountdown {

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

    public NonBlockingCountdown(TimeOut timeOut) {
        this.countdownRunnable = new Runnable() {

            @Override
            public void run() {
                if (seconds > 0) {
                    seconds--;
                    Log.e("NonBlockingCountdown", "seconds=" + seconds);
                    handler.postDelayed(countdownRunnable, COUNTDOWN_INTERVAL);
                } else {
                    // 倒计时结束，可以在这里做一些操作，比如通知用户
                    handler.removeCallbacks(this);
                    timeOut.timeOut();
                    Log.e("NonBlockingCountdown", "timeOut");
                }
            }
        };
    }


    public void start(int s) {
        this.seconds = s;
        handler.postDelayed(countdownRunnable, COUNTDOWN_INTERVAL);
    }

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