package com.kfzs.duanduan.utils.dlg;

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

/**
 * @ Created by Dlg
 * @ <p>TiTle:  HandlerUtils</p>
 * @ <p>Description: 后台循环任务时，可以不用Timer等方式，简便的后台实现循环处理事务</p>
 * @ date:  2017/6/8 13:58
 * @ QQ:    315096953
 */
public class HandlerUtils {

    private Handler mHandler;
    private Runnable mRun;
    private int mIntDelay = 0;
    private boolean mIsBreak = false;

    public boolean ismIsBreak() {
        return mIsBreak;
    }

    /**
     * 设置是否中断循环
     *
     * @param mIsBreak
     */
    public HandlerUtils setmIsBreak(boolean mIsBreak) {
        this.mIsBreak = mIsBreak;
        mHandler.removeMessages(0);
        return this;
    }


    /**
     * 生成主线程的Handler
     */
    public HandlerUtils() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                mRun.run();
                if (!mIsBreak) {
                    removeMessages(0);//防止多次send
                    sendEmptyMessageDelayed(0, mIntDelay);
                }
            }
        };
    }


    /**
     * 投递任务，此事务会工作在UI主线程
     *
     * @param runnable 事务
     * @param ms       循环间隔毫秒数
     */
    public HandlerUtils taskPostInUi(Runnable runnable, int ms) {
        if (ms > 0) {
            mIntDelay = ms;
        }
        mRun = runnable;
        mHandler.sendEmptyMessageDelayed(0, ms);
        return this;
    }


}
