Android Kotlin Handler Runnable 实现循环定时加载 固定次数加载

以下为三种方式

1.延迟执行1次

2.一直循环执行

3.循环执行N次

class MainActivity : AppCompatActivity() {
    
    //执行2
    private val timeRunnable = Runnable {
        Log.e("11111", "11111")
    }
    //循环执行1
    private val flipTime=KTimer(1000){
        Log.e("11111", "11111")
    }
    //循环执行5次
    private val flipTimeCount=KTimer(1000){
        Log.e("11111", "11111")
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
     
        //开始延迟执行1
        KTimer.MAIN_HANDLER.postDelayed(timeRunnable,1000)
        //开始循环执行1
        flipTime.start()
        //循环执行5次
        flipTimeCount.start()
    }   
}
 * <p>
 * count:循环测试
 * </p>
 */
class KTimer(val interval: Long, val count: Int? = null, val call: (() -> Unit)? = null) {
    private var mCountTag = 0
    private val runnable = object : Runnable {
        override fun run() {
            call?.invoke()
            if (count == null) {
                MAIN_HANDLER.removeCallbacks(this)
                MAIN_HANDLER.postDelayed(this, interval)
            } else {
                if (mCountTag > count-2) {
                    MAIN_HANDLER.removeCallbacks(this)
                } else {
                    mCountTag++
                    MAIN_HANDLER.postDelayed(this, interval)
                }
            }

        }
    }

    fun start() {
        stop()
        MAIN_HANDLER.postDelayed(runnable, interval)
    }

    fun stop() {

        MAIN_HANDLER.removeCallbacks(runnable)
    }

    companion object {
        val MAIN_HANDLER = Handler(Looper.getMainLooper())
    }
}

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页